duanlinjian5819 2018-01-03 13:50
浏览 106
已采纳

如何授权然后更新Laravel模型

I'm calling this controller to update a model:

public function update(Request $request, $id)
  {
  $question = Question::find($id);
  $this->authorize('edit', $question); // uses Laravel's built-in Policy framework

  $updateArray = [
    'question' => $request->question,
    'type_based_id' => $request->type_based_id,
  ];

  //$question = Question::where('id', $id);
  $question = $question->update($updateArray);

  // Add the id into the array for return to the client
  $updateArray["id"] = $id;

  return ['message' => 'Question Updated', 'data' => $updateArray];

}

The code above throws a MassAssignmentException on the call to $question->update(). If I uncomment $question = Question::where('id', $id); it works.

I did some logging, and it seems that find() returns an instance of my model (App\Question) and where() returns a builder (Illuminate\Database\Eloquent\Builder)

How can I satisfy both authorize() and update() without making two separate database requests?

Thank you!

  • 写回答

2条回答 默认 最新

  • dongshao6591 2018-01-03 13:59
    关注

    The reason it works using the Query Builder is because it by-passes the mass assignment checks of the model. You are running your own query and not using the Model's update method.

    Question::where()->update is calling update on the Query Builder, not the Model.

    There is no reason to use the query builder when you already have the model instance you are updating, but this isn't actually running any additional SQL queries.


    MassAssignmentException usually means one of the attributes you're passing is guarded in the model. To unguard attributes, either remove them from the $guarded property or add them to the $fillable property of the model. Do NOT use both $guarded and $fillable, you must use one or the other. Read the full documentation here:

    https://laravel.com/docs/5.5/eloquent#mass-assignment

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog