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...