Laravel: Why (Not) Use JSON DB Columns? Practical Examples.

JSON columns in the database seem like a solution if you're not sure about the structure of data. But quite often, they lead to more problems in the future. In this article, I want to show both good and bad cases of using JSON columns with Laravel examples.

If I had to summarize it all in one sentence, it would be this.

Don't use JSON columns if you need to search within that data later.

To rephrase this, it's ok (-ish) to use JSON columns if you just get a single DB record and then process data within that record.

In other words, this isn't good in most cases:

// Migration:
$table->json('options');
 
// Controller:
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();

And this is good:

$user = User::find($id);
// Do JSON manipulation in Laravel from $user->options data

But it's not so black and white. There are various examples. So, let's get practical.


Legit Cases to Use JSON Columns

These are real-life examples of JSON columns that I've found.

Legit Example 1. Translations.

Packages like spatie/laravel-translatable store data in JSON and then get the translations for a single record with this Laravel code:

$newsItem->getTranslations('name');
// returns ['en' => 'Name in English', 'nl' => 'Naam in het Nederlands']

I would argue with myself this is a semi-legit example because...

The full tutorial [8 mins, 1498 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 56 courses (1011 lessons, total 46 h 42 min)
  • 77 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials