logo
podcast Podcast
get help Get Unstuck

Using Eloquent default attribute values instead of MySQL default values

Just a bit cleaner

Joel Clermont
Joel Clermont
2025-09-01

I recently shared a workaround I needed in my tests to handle a model that had a default value set in MySQL.

This prompted some helpful replies from readers that there was an even easier way to handle this than what I had proposed.

Instead of relying on a MySQL default definition to set the value, there's a Laravel feature which does the same thing, and it does it at model creation:

// inside my model
protected $attributes = [
    'example_field' => '[]',
];

These Eloquent default attribute values are specifically for setting a default value on a new model, and they've been around since Laravel 5.7!

One small thing to point out: Notice how my value is wrapped in strings, it's not a bare PHP array.

You need to set the data value as it will eventually be stored in the database. In my case, this is a JSON column cast to a collection, but when stored in the database it's a string, so that's how I need to specify it in the $attributes definition.

I think this is a nice improvement, and I appreciate the suggestion. I'll need to look at any other places I'm using MySQL default values, and see if this same approach would benefit me there.

Here to help,

Joel

P.S. There are a lot of conversations like this in the Mastering Laravel community. Come learn something new and help others at the same time.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.