Dax
Dax

Reputation: 827

Getting no user on update request

I want to update a column from my users table. I linked a button to the PUT request but I'm not getting the user from my request, what am I missing here?

Code

Route:

Route::resource('/admin', 'AdminController')->only(['index','update','destroy'])->middleware('is_admin');  

Controller:

public function update(Request $request, User $user)
{
    $requestData = $request->all();
    dd($requestData, $user, $user->id);
    // return redirect('/admin');
}

View:

{!! Form::open(['action' => ['AdminController@update', $user->id],'method' => 'POST', 'class'=> 'float-right']) !!}
{{Form::hidden('_method','PUT')}}
{{Form::button('Remove points', ['type' =>'submit', 'class' => 'submit-btn'])}}
{!! Form::close() !!}

DD output:

array:2 [▼
  "_token" => "5AOzOmyktXUiuW5OJNQbVOuDuFtEWgkH1h1Zocgo"
  "_method" => "PUT"
]
User {#242 ▼
  #fillable: array:6 [▶]
  #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: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #rememberTokenName: "remember_token"
}
null

Upvotes: 1

Views: 184

Answers (1)

Elias Soares
Elias Soares

Reputation: 10254

TL;DR;

Rename your $user attribute to $admin.

Explaination

Laravel will only inject some model when you define a Route Model Binding pattern:

Your route must accept a parameter with the same name of the attribute you are trying to inject, for example:

PATCH admin\{user}

And your controller's method must have an attribute with the same name:

public function update(User $user) { /** **/ }

Since you are defining your route using the Route::resource('admin', ...) method, laravel will automatically name that parameter with the same name of the resource, so your route will look like this;

PATCH admin\{admin}

That's why Laravel can't inject the model properly, so it injects just an empty model (the default behavior of dependency injection is to instantiate the class and inject it).

So your method's attribute must be named $admin:

public function update(Request $request, User $admin) { /** **/ }

This way Laravel can see that this parameter should be filled with a Model loaded with the ID given on URL.

Upvotes: 4

Related Questions