Making a new Model

Last updated on May 1st, 2021.

What is a model?

Models are php classes which act as a gateway to the database. They are an interface to real data, and you will use them in your code to write or modify the data or to pull the data out of the database for display.

Generating a model

artisan make:model UserSetting will generate a new model class. This generated class will have everything you need to get started, and you can use the generated code unedited immediately with no modifications.

Mass assignment and $fillable theory

While the model is ready to use right away, there is one common modification it is recomendable to do immediately.

A common example of setting values in the database via a model might look like this:

$userSetting = new UserSetting();

$userSetting->layout=$userSubmittedSettings['layout'];
$userSetting->display_name=$userSubmittedSettings['display_name'];
$userSetting->save();

Mass assignment allows you to hugely simplify this by passing the full $userSubmittedSettings array to the model.

$userSetting = UserSetting::create($userSubmittedSettings);

However, this type of shortcut is commonly a place where data is inadvertantly changed when the $userSubmittedSettings contains unexpected fields which would then be processed along with the rest.

$fillable is a white list of fields which should be processed when using mass assignment.

Setting fillable on your model

Using the example field names above, one would add to the model:

    protected $fillable = [
       'layout',
       'display_name',
    ];

Of course you will need to replace the three fields in this example with column names you've added in your migration. You can comfortably make most fields fillable like this, however you should think carefully about each specific field and exclude it from this list if there are security concerns around the value changing unexpectadly. Examples of this are password or email fields.