logo
podcast Podcast
get help Get Unstuck

What is the difference between Eloquent array and JSON casts?

When would you use one over the other?

Joel Clermont
Joel Clermont
2024-07-10

I was asking myself this question the other day. The docs lump them together interchangeably.

And when I was playing around in an app, they both produced the same result. I thought maybe if I was using a string column type instead of a JSON column type, maybe it would behave differently, but it didn't.

So what's the difference?

Shortest tip ever: There is no difference at all. They are two names for the same exact cast.

You can see this in Laravel source for yourself:

// Illuminate\Database\Eloquent\Concerns\HasAttributes.php
protected function castAttribute($key, $value)
{
    // snipped out just the relevant part of the method
    switch ($castType) {
        case 'array':
        case 'json':
            return $this->fromJson($value);
    }
}

Both casts result in the exact same code path. I typically use array because it is accessed on the model as an associative array, but it really doesn't matter.

Fun fact: ask your AI chatbot of choice to explain the difference, and it will confidently hallucinate all sorts of wrong information in reply.

Here to help,

Joel

P.S. Learning to explore and read Laravel source code is a great way to level up your understanding of the framework.

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.