doubo7131 2018-06-10 22:07
浏览 54
已采纳

如何使用Laravel 5.6中的Route Model Binding更新用户

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.

  • 写回答

1条回答 默认 最新

  • douqiangchuai7674 2018-06-10 22:28
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗