Issue
I have a profile view where i would like to update users profile.
my Controller:
public function update(Request $request, User $user)
{
$validatedData = $request->validate([
'name' => 'required',
'email' =>'required|email',
'key' => 'required'
]);
// dd($user);
$user->update($validatedData);
// User::whereId($user->id)->update($validatedData);
return back()->with('flash', 'Successfully updated profile.');
}
I'm injecting a model's instance into my route. When i dd($user)
i get the current user instance.
Now i would like to update the user with the validatedData. But unfortunately this
$user->update($validatedData);
is not working. I don't understand why...
This User::whereId($user->id)->update($validatedData);
is working but it feels very strange to call on user
the user->id
.
Solution
It's important to understand the difference between the two similar calls.
whereId()
returns an instance of the query builder so you're no longer calling methods on the model. So update() is a query builder call, not a model call.
find()
(or route model binding) would returning an instance of the Model. Therefore, you'd be calling update() from the Model itself.
Eloquent models have mass assignment protection built in. My assumption is one or more of your columns are not in the $fillable array in your model. Either explicitly add every column into the $fillable array or remove the $fillable array and explicitly add every column that should not be mass assigned to the $guarded array.
https://laravel.com/docs/5.6/eloquent#mass-assignment
Answered By - Devon
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.