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

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

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。