Search code examples
laravellaravel-5mass-assignment

Laravel MassAssignmentException from firstOrNew by id


I am attempting to save data using Laravel's firstOrNew method, which is producing a MassAssignmentException error.

I don't understand why the firstOrNew method should trigger a mass assignment exception since it is merely looking at the database, not attempting to save anything. From the docs:

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database.

Why then, should my code be throwing a MAE:

$tour = Tour::firstOrNew(array('id' => $this->request['id']));

As I understand, all that the above code is saying is basically "look and see if there is a row in the database with that ID, if so then return the row, if not, then create a new object with the relevant properties". It isn't saving any data so what is the problem?

Note that the error only occurs if the row doesn't exist.


Solution

  • firstOrNew() uses newInstance() which creates new model using constructor. Constructor uses fill() method which is Mass Assigment. That's why you're getting an exception.

    So, you need to set $fillable array to use firstOrNew()