PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 3, 2022

[FIXED] How to update an user using Route Model Binding in Laravel 5.6

 February 03, 2022     laravel-5, php     No comments   

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. enter image description here 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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing