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!
Great article! Just a quick question – if I have 20 fields in my table, do I have to add all of them in the fillable array for them to be saved?
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.
What about using protected $quarded to do the opposite?
Thank you, Povilas.
Had some issues with student form field, got solved because of the above simple line code.
I set $guarded = []; (mostly) all the time.
So everything is fillable.
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.