PHP

Querying and Updating JSON Data in Database Columns with Eloquent

Learn to effectively query and update structured JSON column data in your database using Laravel Eloquent's powerful `->>` operator and dot notation for efficiency.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $casts = [
        'details' => 'array',
    ];

    protected $fillable = ['name', 'details'];
}

// Migration example (products table):
// Schema::create('products', function (Blueprint $table) {
//     $table->id();
//     $table->string('name');
//     $table->json('details')->nullable(); // Store JSON data
//     $table->timestamps();
// });

// Example Usage:
// Creating a product with JSON details
$product = Product::create([
    'name' => 'Smartphone X',
    'details' => [
        'color' => 'Black',
        'storage' => '128GB',
        'features' => ['camera', '5G', 'NFC']
    ]
]);

// Querying products where 'color' in details is 'Black'
$blackPhones = Product::where('details->color', 'Black')->get();

// Querying products where 'storage' in details is '128GB' AND '5G' is in features array
$advancedQuery = Product::where('details->storage', '128GB')
                        ->whereJsonContains('details->features', '5G')
                        ->get();

// Updating a specific JSON property
$product->update(['details->color' => 'White']);
How it works: This snippet demonstrates how to store, query, and update JSON data directly within a database column using Eloquent. By casting the `details` attribute to `array` in the model, Eloquent automatically handles serialization and deserialization. You can query specific nested keys using the `->` operator (e.g., `details->color`) and even check for existence within JSON arrays with `whereJsonContains`, providing powerful querying capabilities.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs