PHP
Querying JSON Columns with Eloquent's whereJsonContains
Learn to effectively query JSON data stored in database columns using Laravel Eloquent's `whereJsonContains` method for filtering records based on array values.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $casts = [
'tags' => 'array', // Cast the 'tags' column to a PHP array
];
}
// Assuming a 'products' table with a 'tags' JSON column:
// | id | name | tags |
// |----|-----------|-----------------------|
// | 1 | Laptop | ["electronics", "tech"] |
// | 2 | Keyboard | ["tech", "accessory"] |
// | 3 | Monitor | ["electronics"] |
// Usage example in a controller or service:
// Find products that have the 'tech' tag
// $techProducts = Product::whereJsonContains('tags', 'tech')->get();
//
// foreach ($techProducts as $product) {
// echo "Product: {$product->name}
"; // Outputs: Laptop, Keyboard
// }
// Find products that have the 'electronics' tag
// $productsWithElectronicsTag = Product::whereJsonContains('tags', 'electronics')->get();
// foreach ($productsWithElectronicsTag as $product) {
// echo "Product: {$product->name}
"; // Outputs: Laptop, Monitor
// }
How it works: Laravel Eloquent provides convenient methods for querying JSON columns in your database. The `whereJsonContains` method allows you to check if a JSON array column (or a specific path within a JSON object) contains a given value. This is highly useful for filtering records based on tags, settings, or other dynamic data stored in JSON format, without resorting to complex raw SQL queries.