Re-styled Laravel logo

Eloquent Models - First Impressions

05 October 2020

I've just started building my gardening application and thought I'd note down a few of my first impressions getting into using Eloquent models. Here are a few of my thoughts:

They're easy to work with #

Yup, I managed to do what I would had done with vanilla PHP and home-rolled CSV functions in 5 hours in about half an hour.

Most of the code is already written #

When you're using eloquent models you barely have to write any code at all. The only thing the class really needs to do is extend the Eloquent Model class and you get a whole bunch of functionality. Sometimes you'll also need to define some relationships between different models - eg. an author owning a blog post.

The main hassle with eloquent models is writing the migrations which will generate the database tables and rows you need. It was quite slow-going looking throught the laravel documentation to find out what to write to create data of a certain type. I don't think this is laravel's fault or anything - there is always going to be some complexity in defining the data that your application needs.

Protection from mass assignment #

Laravel does not let you set a big load of database rows from a request without your careful supervision. You can't use an array to create or update an eloquent model unless all the properties you are setting are set to "fillable". Alternatively, you can set some properties as "guarded". This will mean the default is that you can fill create/update the model with an array. But the properties set to "guarded" can not be filled with an array.

In my applications I think I will be using the "fillable" model where I expressly declare anything that can be filled with an array. I also think I might avoid using arrays to fill up models anyway so I can keep everything explicit about what is going on. We'll see where this takes me.

Back to blog