PHP
Query and Update JSON Columns in Laravel Eloquent Models
Learn how to effectively store, query, and manipulate structured data within JSON columns using Laravel Eloquent's powerful features.
// 1. In your migration file (e.g., add_settings_to_users_table.php):
Schema::table('users', function (Blueprint $table) {
$table->json('settings')->nullable();
});
// 2. In your Eloquent Model (e.g., App\Models\User.php):
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $casts = [
'settings' => 'array', // Automatically cast 'settings' JSON column to a PHP array/object
];
protected $fillable = ['name', 'email', 'password', 'settings'];
}
// 3. Usage examples in a Controller or elsewhere:
use App\Models\User;
// Create a user with JSON settings
$user = User::create([
'name' => 'Alice',
'email' => '[email protected]',
'password' => bcrypt('password'),
'settings' => [
'theme' => 'dark',
'notifications' => [
'email' => true,
'sms' => false,
],
],
]);
// Retrieve and access JSON data
$user = User::find(1);
echo $user->settings['theme']; // Output: dark
echo $user->settings['notifications']['email']; // Output: 1 (true)
// Update JSON data directly
$user->settings['theme'] = 'light';
$user->settings['notifications']['sms'] = true;
$user->save(); // Laravel automatically detects JSON changes and updates
// Query JSON data (where conditions)
$darkThemeUsers = User::where('settings->theme', 'dark')->get();
$emailNotifUsers = User::where('settings->notifications->email', true)->get();
// Query JSON data (whereJsonContains) for array values
// Example: If 'tags' was a JSON array column like ['laravel', 'php']
// User::whereJsonContains('tags', 'laravel')->get();
How it works: This snippet demonstrates how to effectively work with JSON columns in Laravel Eloquent. By casting a JSON column to `array` in the model's `$casts` property, you can interact with the JSON data as a standard PHP array or object. Eloquent automatically handles serialization and deserialization. It also shows how to easily query specific keys within JSON columns using `->` notation in `where` clauses and how to update nested JSON values, which Laravel saves efficiently.