0

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!

Witt
  • 477
  • 4
  • 11
  • Not really clear what you're asking. Authorization has nothing to do with your update call. MassAssignmentException usually means one of the attributes you're passing is guarded in the model. – Devon Bessemer Jan 03 '18 at 13:55

2 Answers2

1

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

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • Thank you - I had read the mass assignment docs, but mis-understood the meaning of the term. [This answer](https://stackoverflow.com/a/22279580/3852890) clarified it for me. – Witt Jan 03 '18 at 14:13
0

MassAssigntmentException is due to the fields you are updating not being fillable and therefor being guarded from assignment, to achieve this you need to set these on the Question class.

public class Question
{
    protected $fillable = [
        'question',
        'type_based_id',
    ];
}
mrhn
  • 17,961
  • 4
  • 27
  • 46