PHP
Query JSON Columns in Eloquent Models
Learn how to effectively query and update JSON type columns directly within your Laravel Eloquent models, enabling flexible data storage and retrieval.
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $casts = [
'options' => 'array', // Cast JSON column to PHP array
];
// Migration: $table->json('options')->nullable();
}
// Create a product with JSON data
$product = Product::create([
'name' => 'Laptop',
'options' => [
'color' => 'silver',
'storage' => '512GB SSD',
'features' => ['backlit_keyboard', 'fingerprint_reader'],
],
]);
// Query products where a specific JSON key has a value
$silverProducts = Product::whereJsonContains('options->color', 'silver')->get();
// Query products where a value exists within a JSON array
$fingerprintProducts = Product::whereJsonContains('options->features', 'fingerprint_reader')->get();
// Update a specific key within a JSON column
$product->update([
'options->storage' => '1TB SSD',
]);
// Accessing JSON data as an array
echo $product->options['color']; // 'silver'
How it works: Laravel Eloquent allows direct interaction with JSON type columns in your database. By casting a JSON column to an `array` in your model's `$casts` property, you can treat it as a native PHP array. Eloquent provides methods like `whereJsonContains()` and dot notation (`column->key`) for efficiently querying and updating specific keys or values within these JSON structures, simplifying complex data management.