I am learning laravel and I have the following error I would like to know if someone could help me to solve it. I have a model called User and a controlled call UserController,I try to use model binding to create the edit, update and destroy. In the edit function I have the following code.
public function edit(User $user)
{
dd($user);
}
This function returns:
User {#191 ▼
#fillable: array:3 [▶]
#dates: array:1 [▶]
#hidden: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
#forceDeleting: false
}
If I delete the model User
public function edit($user)
{
dd($user);
}
Returns the id of the user being edited in this case /usuario/24/edit
"24"
The routes are declared as follows
Route::resource('/usuario','UsuarioController');
I would like to know if someone knows how to fix this problem since the function should refer to the User model and later to the $ user variable, if someone knows how to fix it or if I am doing something wrong it would be of great help
There's no problem on what you're reporting here. It's the desired Laravel Framework behavior.
If you type hint the Model as you did on your first example, Laravel will under the hood try to do:
But when you don't type hint, laravel don't know what model should be loaded with that ID, so it will just pass the
id
that user gave on request parameters.Change your code to look like this: