PHP
Querying JSON Column Data in Eloquent
Perform advanced queries on JSON data stored in database columns directly with Laravel Eloquent, using dot notation for nested values and various comparison operators.
use App\Models\Product;
// Example 1: Querying a top-level JSON key
$redProducts = Product::where('options->color', 'red')->get();
// Example 2: Querying a nested JSON key
$largeProductsWithStock = Product::where('details->sizes->L->in_stock', true)->get();
// Example 3: Querying a JSON array
$productsWithTagA = Product::whereJsonContains('tags', 'tagA')->get();
// Example 4: Querying a JSON array for any item greater than a value
$productsWithRatingAbove4 = Product::whereJsonLength('ratings', '>', 4)->get();
How it works: Laravel Eloquent provides excellent support for querying JSON columns in databases like MySQL (5.7+), PostgreSQL, and SQLite (3.38+). You can access keys within a JSON column using the `->` operator (dot notation) directly in your `where` clauses, even for deeply nested values. `whereJsonContains` allows checking if a JSON array contains a specific value, and `whereJsonLength` helps query based on the length of a JSON array.