I have Many To Many relationships between User Model & Wallet Model:
Wallet.php:
public function users() {
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}
And User.php:
public function wallets() {
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');;
}
Then at Blade, I tried this:
#forelse($user->wallets as $wallet)
<tr>
<td>{{ $wallet->name }}</td>
<td>{{ $wallet->pivot->balance }}</td>
<td></td>
</tr>
#empty
<td colspan="5" class="text-center">No wallet exist</td>
#endforelse
As you can see I have passed two parameters as route name user.WalletTransaction which is a link:
{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$wallet->users()->usr_id]) }}
And on web.php:
Route::get('wallet/transaction/{wallet}/{user}', 'Wallet\UserWalletController#WalletTransaction')->name('user.WalletTransaction');
But it shows me this error:
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$usr_id
However usr_id is the id of users at users table:
And the pivot table structure, user_wallet, goes like this:
So how can I properly add the user id to that link?
I would really appreciate any idea or suggestion from you guys about this...
Thanks.
UPDATE #1:
Result of <a href="{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$user->id]) }}" class="fa fa-exchange text-dark mt-1" /> shows two links!
$wallet->users() returns a collection, so you need to iterate over it like you're iterating over wallets
#forelse($wallet->users() as $user)
<td>
<a href="{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$user->id]) }}" class="fa fa-exchange text-dark mt-1" />
</td>
[...]
Related
I'm working with Laravel 8 and I have made a table like this at Blade:
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tr>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Actions</th>
</tr>
#foreach($roles as $role)
#if(count($role->users))
#foreach($role->users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $role->name }} | {{ $role->label }}</td>
<td>
<form action="{{ route('levels.destroy' ,$user->id) }}" method="post">
#method('DELETE')
#csrf
<div class="btn-group btn-group-xs">
Edit
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</form>
</td>
</tr>
#endforeach
#endif
#endforeach
</table>
</div>
And the result perfectly showing up:
But now I got problem with Edit & Delete buttons that I have specified $user->id as parameter for both of them.
And when I hover over the buttons I can see the user id properly defined:
But when it comes to edit method which is using Route Model Binding, it does not find the user:
public function edit(User $user)
{
dd($user->id); // return null
}
However if I do not use Route Model Binding and say this instead:
public function edit($id)
{
dd($id); // return 1
}
It properly shows the user id!
I don't know why the Route Model Binding not working here, so if you know what's going wrong or how to fix this issue, please let me know...
You are trying to access the User Model which in this case doesn't know what id is, so you should be passing the id of the user to the edit route using either Get by passing it to the url endpoint , so now you can get it like
public function edit($id)
{
dd($id); // return null
}
or by sending it as a POST form and get it like
public function edit(Request $request)
{
dd($request->id); // return null
}
I saw comments, your resource controller name is not matching with your variable name "$user".
You can look here on official laravel docs.
In your situation, this might help;
Route::resource('levels', LevelController::class)->parameters([
'levels' => 'user'
]);
I have a many-to-many relationship between my User and Wallet models.
Wallet Model
public function users()
{
return $this->belongsToMany(User::class, 'user_wallet', 'user_id', 'wallet_id');
}
User Model
public function wallets()
{
return $this->belongsToMany(Wallet::class, 'user_wallet', 'user_id', 'wallet_id')->withPivot('balance');;
}
Then in my Blade file, I tried the following.
#forelse($user->wallets as $wallet)
<tr>
<td>
{{ $wallet->name }}
</td>
<td>
{{ $wallet->pivot->balance }}
</td>
<td>
<a href="{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$user->id]) }}" class="fa fa-exchange text-dark mt-1" />
</td>
</tr>
#empty
<td colspan="5" class="text-center">No wallet exist</td>
#endforelse
It works fine, but the problem is, it shows two links in the table for one user. However, it should be showing one.
And if I do:
#forelse($user->wallets as $wallet)
{{ count(array($user)) }}
#empty
<td colspan="5" class="text-center">
No wallet exist
</td>
#endforelse
The result would be 1.
The problem is coming from 'userId' => $user->id of the link. Because if I remove it, only 1 link would appear, which is correct. But still, I do need the userId and don't know how to pass that into the route name.
So what's going wrong here? I need one link for each user, and I don't know why it prints two of them.
#forelse($user->wallets as $wallet)
<tr>
<td>
{{ $wallet->name }}
</td>
<td>
{{ $wallet->pivot->balance }}
</td>
<td>
<a href="{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$user->id]) }}" class="fa fa-exchange text-dark mt-1" />
</td>
</tr>
#empty
<td colspan="5" class="text-center">No wallet exist</td>
#endforelse`
Doesn't $user->wallets returns collection of all wallets associated with each user?
maybe you need to check if any user has more than one wallet or if you want to show only one you can user $user->wallets[0] to show the first wallet model since its a collection
I've encountered a problem with the Kyslik\Column-sortable package for Laravel which has frustrated me for weeks now. :)
The sorting links displays correctly, but when I click on one of the sorting links, I get the following error:
🧨 Trying to get property 'title' of non-object (View: C:\wamp64\www\GeekCollector\resources\views\Lp\show.blade.php)
What's even more strange is that the route goes to the BrowseResults view, but the message sais that the error was encountered in the Show view.
If I remove all the sortable related stuff from the BrowseResults view, the Show view works perfectly.
Here is my model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;
use Kyslik\ColumnSortable\Sortable;
class Lp extends Model
{
use HasFactory;
use Sortable;
public $sortable = ['title', 'artist', 'year'];
}
Here is my BrowseResults controller method:
public function browseResults(Request $request)
{
$chosenCategory = $request->category;
$lps = Lp::where('category','like','%'.$chosenCategory.'%');
$result = $lps->sortable('title')->paginate(5);
return view('Lp.browseResults', compact('result'));
}
And here is my blade view:
<x-app-layout>
<x-slot name="header">
<h1 class="font-semibold text-xl text-gray-800 leading-tight">
Lp-skivor
</h1>
</x-slot>
#sortablelink('title')
#sortablelink('artist')
#sortablelink('year')
<table>
<tr>
<td>Titel</td>
<td>Artist</td>
<td>Kategori</td>
<td>Plats</td>
<td>Position</td>
</tr>
#foreach ($result as $lp)
<tr>
<td>
{{ $lp->title }}
</td>
<td>{{ $lp->artist }}</td>
<td> {{ $lp->category }}</td>
<td>{{ $lp->place }}</td>
<td>{{ $lp->position }}</td>
<td>
Uppdatera
</td>
<td>
<form action="{{ route('lp.destroy', $lp->id) }}" method="post">
#csrf
#method('DELETE')
<button type="submit">Ta bort</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $result->appends(\Request::except('page'))->render() !!}
</x-app-layout>
The route looks like this:
Route::post('/lp/browse-results', [LpController::class, 'browseResults'])->name('lp.browseResults');
Thanks very much in advance for your help!
All the best!
I am working in Laravel 7, pulling data from my db and showing the student his/her score on the scores page in percentage via the following codes.
In my StudentOperationController.php
public function show_result($id) {
$data['result_info'] = Oex_result::where('id', $id)->get()->first();
$data['student_info'] = Oex_students::select(['oex_students.*', 'oex_exam_masters.title', 'oex_exam_masters.exam_date'])->join('oex_exam_masters', 'oex_students.exam', '=', 'oex_exam_masters.id')->where('oex_students.id', Session::get('id'))->get()->first();
return view('student.show_result', $data);
}
and in my show_result.blade.php
<h2>Result Information</h2>
<table class="table">
<tr>
<td>Number Correct</td>
<td>{{ $result_info->yes_ans }}</td>
</tr>
<tr>
<td>Number Incorrect</td>
<td>{{ $result_info->no_ans }}</td>
</tr>
<tr>
<td>Total</td>
<td>{{ round($result_info->yes_ans / ($result_info->yes_ans + $result_info->no_ans) * 100 , 1) }} %</td>
</tr>
</table>
The reason I show this is that it works as expected. this is within the students dashboard. In my admin, I am trying to do the same thing and show that students data for his/her exam result. In my database, I have a json type data for example: {"2":"YES","3":"YES","8":"YES"}. I am still learning Laravel and am stuck on how to get this data to my admin. I am clearly doing something wrong and am in need of assistance. Here is what I have tried:
AdminController.php
public function manage_students($id)
{
$data['result_info'] = Oex_result::where('id', $id)->get()->first();
// dd($data);
$data['student_info'] = Oex_students::select(['oex_students.*', 'oex_exam_masters.title', 'oex_exam_masters.exam_date'])->join('oex_exam_masters', 'oex_students.exam', '=', 'oex_exam_masters.id')->where('oex_students.id', Session::get('id'))->get()->first();
$data['exams'] = Oex_exam_master::where('status', '1')->get()->toArray();
$data['students'] = Oex_students::select(['oex_students.*', 'oex_exam_masters.title as exam_name'])
->join('oex_exam_masters', 'oex_students.exam', '=', 'oex_exam_masters.id')
->get()->toArray();
return view('admin.manage_students', $data);
}
and in my manage_students.blade.php, I have
<tbody>
#foreach($students as $key => $student)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $student['name'] }}</td>
<td>{{ $student['email'] }}</td>
<td>{{ $student['mobile_no'] }}</td>
<td>{{ $student['exam_name'] }}</td>
{{-- <td>N/A</td> --}}
<td>{{ round($result_info->yes_ans / ($result_info->yes_ans + $result_info->no_ans) * 100 , 1) }} % </td>
#if($student['status']== 1)
<td><input data-id="{{ $student['id'] }}" class="student_status" type="checkbox" name="status" checked></td>
#else
<td><input data-id="{{ $student['id'] }}" class="student_status" type="checkbox" name="status"></td>
#endif
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
In doing this I get the error Too Few arguments to function ... 0 passed and exactly 1 expected
I am unable to replicate what I have for the student dashboard and because of my lack of Laravel knowledge, I am having trouble solving this issue. So, any help would be greatly appreciated. If I am missing anything, please let me know so I can edit my question. Thanks in advance.
Edit: manage_students route:
Route::get('admin/manage_students', 'AdminController#manage_students');
Edit Number 2:
Too few arguments to function App\Http\Controllers\AdminController::manage_students(), 0 passed and exactly 1 expected
C:\laragon\www\lionsfieldtest\app\Http\Controllers\AdminController.php:146
Referring to this line:
public function manage_students($id)
Edit Number 3:
in resources/views/layouts/app.blade.php
<li class="nav-item">
<a href="{{ url('admin/manage_students') }}" class="nav-link">
<i class="nav-icon fas fa-school"></i>
<p>
Student Management
</p>
</a>
</li>
Edit number 4:
The manage_student page brings in data from a number of student's exam results
This function request $id;
public function manage_students($id)
This route doesn't pass one
Route::get('admin/manage_students', 'AdminController#manage_students');
As I can see you are filtering by results which in this case you need $result id
Route::get('admin/manage_student/{id}', 'AdminController#manage_students');
So you have to pass result ID, but lets assume there is a default results id
public function manage_students($id=2)
then this route works because $id is optional/predefined.
Route::get('admin/manage_students', 'AdminController#manage_students');
And if you pass an ID it will use
Route::get('admin/manage_student/{id}', 'AdminController#manage_students');
Make 2 routes and make parameter optional/predefined.
if you go to /admin/manage_student it will use ID 2
but if you pass /admin/manage_student/5 it will use 5
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.
#foreach ($patients as $patient)
<tr>
<td>{{ $patient->pID }}</td>
<td>{{ $patient->pName }}</td>
<td>{{ $patient->pAddress }}</td>
<td>{{ $patient->pBday }}</td>
<td>{{ $patient->pPhone}}</td>
<td>{{ $patient->pEcon }}</td>
<td>{{ $patient->pDreg }}</td>
<td></td>
<td>
<a href="{{ URL::to('visit/'.$patient->pID) }}">
<img src="../images/viewvisit.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('addeditvisit/'.$patient->pID) }}">
<img src="../images/visit.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('editpatient/'.$patient->pID) }}">
<img src="../images/update.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('deletepatient/'.$patient->pID) }}">
<img src="../images/delete.png" style="width:30px; height:30px;">
</a>
</td>
</tr>
#endforeach
what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.
I'm currently stuck with this controller function.
public function index(Request $request) {
$doctors = Doctor::where('dStatus', 0)
->lists('dName', 'dID');
$beds = Bed::where('bStatus', 0)
->lists('bName', 'bID');
$patient = Patient::patient();
// $uri = $request->path('patient');
return View::make('pages.addeditvisit', [
'doctors'=>$doctors,
'beds'=>$beds,
'patient'=>$patient->pID
]);
}
This is late. But for the benefit of others like me;
If you do not have to do it in a method like the answers above have shown, As of Laravel 5.0 (Not sure about previous versions), you can do
$request->route('id');
That returns the value of the id parameter on the route.
Or just use it within Blade: {{ request()->route('id') }}
Basically when you are defining the routes, you use something called route parameters, something like this
Route::get('/visit/{id}', 'Controller#someMethod');
This id will be available as a parameter in your handler funtion,
public function someMethod($id) {
// you have the id here
}
Simple example:
as link=> example.com/user/1
as rout=> Route::get('user/{id}', 'UserController#user');
as UserController function
public function user($id){
echo $id;
}
output => 1
The trick is to declare the url's structure at routes including the id, for example:
// {{ URL::to('editpatient/'.$patient->pID) }}
Route::get('editpatient/{patientId}', 'MyController#index');
Then, just inject the id in the controller's function:
public function index($patientId){
// $patientId is the variable from url
}
Please refer to the answered question for how to get a parameter from a route. But if you stumbled on this old Laravel thread looking for how to retrieve a model by its ID, the simplest way is to instantiate the model in the controller's request parameter:
Route::get('/retrieve_product/{product}', 'SearchController#getProduct');
Then over in your controller, you simply need:
use App\Product;
class SearchController extends Controller
{
public function getProduct( Product $product ) {
return $product;
}
}
That's it. No find, no where, no get, no first etc.
So, in this example, if you visit /retrieve_product/1 the first product is returned to you.
Route::get('post/user/{id}','ProductController#allpost')->where('id', '[0-9]+');
Controller
public function allpost($id)
{
$products = Product::where('uploadby', $id)->orderBy('created_at','desc')->paginate(5); <br>
return view('product.user_product')->with('products', $products);
}