简体   繁体   中英

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

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 .

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

If you try update remenber declare fields into $fillable property on model.

protected $fillable = ['name','email','key'];

After that you can update the model using Route Model Binding

I ran into this yesterday. I was using model route binding for a delete action. So, I passed the ONLY the user ID to the DELETE route and hinted {user} in the route like this:

Route::middleware(['auth:sanctum', 'verified'])
    ->delete('/users/delete/{user}', [UserController::class, 'delete'])
    ->name('users.delete')
    ->where('id', '[0-9]+');

And the controller worked so simply like this:

  public function delete(User $user) {

    $user->delete();

    return Redirect::route('users')
      ->with('success', "User $user->id $user->name was deleted successfully");
  }

I was glad to have the user object available for the flash message.

Using the same process, I wanted to add a user update action. So, I did the same thing, I sent only the user ID to the PUT route and hinted user again:

Route::middleware(['auth:sanctum', 'verified'])
  ->put('/users/edit/{user}', [UserController::class, 'edit'])
  ->name('users.edit')
  ->where('id', '[0-9]+');

I got to the controller and could dump the user object. So, I tried a simple update something like this:

 public function edit(User $user)
  {
    $user->update(
      [
        'name' => user->name,
        'email' => user->email,
      ]
    );
  }

I received no errors and the update returned true. But my data did not reflect the intended changes...

Then, in the car a while later, I realized, with model route binding, the route is querying the existing user in the database. So, if I assign the values from that user object in the controller, there will be no change!

::facepalm::

So, it makes sense that the delete action would work fine, but for an update action, you must assign the changed values from the request during the update. Because the values in the request would likely be different than the existing user objects values:

      public function edit(Request $request, User $user)
      {
        $user->update(
          $request->validate([
            'name' => 'required|string',
            'email' => 'required|email',
          ])
        );
    
        return Redirect::route('users')
          ->with('success', "User $user->id $user->name was updated successfully");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM