如何授权然后更新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!

查看全部
duanlinjian5819
duanlinjian5819
2018/01/03 13:50
  • laravel
  • php
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复