Laravel 5.5 form model binding User

1.6k Views Asked by At

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

2

There are 2 best solutions below

2
On

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:

$user = User::findOrFail($user)

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:

// At the top of your controller add a use statement
use App\User;

class UserController extends Controller 
{
    //                    ▼ This is the typehint 
    //                         ▼ The parameter name should be the same resource name used on route
    public function edit(User $usuario)
    { 
        dd($usuario); 
    }
}
0
On

For Model Binding to work in the controller action you have to use a variable name that match the paramenter you use in your Route declaration, try as follow:

public function edit(User $usuario)

Since in your route you declared tu use "usuario" as parameter the model binding search for a variable of the same name.

You can check your parameter name with php artisan route:list

It is also written in the laravel docs, on model binding:

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name