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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化