PHP
Querying and Updating JSON Columns in Laravel Eloquent
Learn how to effectively query and manipulate JSON data stored directly within database columns using Laravel Eloquent's convenient syntax.
// Migration example (add to a table migration):
$table->json('settings')->nullable();
// Example Model usage:
class User extends Model {
protected $casts = [
'settings' => 'array',
];
}
// Querying:
$usersWithSpecificTheme = User::where('settings->theme', 'dark')->get();
$usersWithEmailPrefs = User::where('settings->preferences->email_notifications', true)->get();
// Updating:
$user = User::find(1);
$user->update(['settings->theme' => 'light']);
// Or retrieve, modify, save (recommended for complex changes):
$settings = $user->settings; // Because of $casts, this will be an array
$settings['preferences']['newsletter'] = false;
$user->settings = $settings;
$user->save();
How it works: This snippet demonstrates how to seamlessly interact with JSON columns in your database using Eloquent. It covers defining a JSON column in a migration, casting it to an array in your model for easy PHP access, and then performing direct queries and updates on nested JSON properties using a `->` syntax. This makes it straightforward to manage structured data within a single column, avoiding the need for separate tables for simple key-value pairs or preferences.