Don’t forget the fillables!

Just a quick tip. I’ve noticed a really typical mistake by developers, which caused some headache for myself and for others – you add a new field into the database table, but for some reason it isn’t automatically saved.

The full situation – you’ve added a field into a database, made and run a migration for that, and then just add it to the form. Of course, Laravel should take care of it with Model::create($request->all()), right? But sometimes it doesn’t. Because you forget to add a new field to the $fillable array.

In the Eloquent models there’s an array which defines what fields are automatically filled with create() method:

protected $fillable = ['first_name', 'last_name', 'email'];

So, for example, if you add a new field address to this table, please don’t forget to add it to $fillable array – otherwise it won’t be saved. The worst part is that Laravel won’t throw any error – it would just save the row without that column value.

As I said – just a quick tip. Hope that helps!

Like our articles?
Check out our Laravel online courses!

6 COMMENTS

    • Hi Kenold,
      In theory – yes. But it depends – for example, created_at and updated_at don’t need to be there. And another question is do you really need all 20 fields, feels like too many for me, maybe you should separate them into several tables? But if that’s your project’s task, then it’s absolutely fine.

    • Thanks for comment Lars. It may be more convenient, but $fillable are my personal preference for readability, specifying which columns are editable, for developers coming to the project it gives additional information.

LEAVE A REPLY

Please enter your comment!
Please enter your name here