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

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

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?