Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Using Eloquent default attribute values instead of MySQL default values

Just a bit cleaner

Joel Clermont
Joel Clermont
2025-09-01

From our daily Laravel tips email. Get the next one in your inbox.

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.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.