Reputation: 2422
I'm having a UsersController in this path app/Http/Controllers/Admin with the default edit function
public function edit(User $user)
{
dd($user);
}
and this route
Route::namespace('Admin')->group(function (){
Route::get('adminUsers', 'UsersController@index')->name('adminUsers');
Route::get('adminEditUser/{id}', 'UsersController@edit')->name('adminEditUser');
Route::get('adminDeleteUser/{id}', 'UsersController@delete')->name('adminDeleteUser');
});
So all controllers get the "Admin" folder name before it instead of adding it for every controller. Now I have this view
@foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td><a href="{{ route('adminEditUser', $user->id) }}" class="btn btn-sm btn-primary">Edit</a>
<a href="{{ route('adminDeleteUser', $user->id) }}" class="btn btn-sm btn-primary">Delete</a></td>
</tr>
@endforeach
The edit link opens this url
http://127.0.0.1:8000/adminEditUser/1
And the $user object doesn't have any user data (user with id 1 already exists)
App\User {#1419 ▼
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
Why is that and how to solve this?
Upvotes: 0
Views: 110
Reputation: 50491
Your route parameter is named id
not user
. The parameter name has to match what you are type hinting for the Implicit Route Model Binding to work.
Route::get('adminEditUser/{user}', 'UsersController@edit')->name('adminEditUser');
Now it will match the method signature you have:
public function edit(User $user)
In your case you were just getting Dependency Injection of a new User
object instead of any Model Binding happening.
"Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name."
Laravel 6.x Docs - Routing - Route Model Binding - Implicit Binding
Upvotes: 1