Query JSON Columns Easily in Laravel Using whereJsonContains()
Laravel's whereJsonContains() method makes it easy to query JSON columns using Eloquent. Whether you're storing user preferences, roles, or tags, you can search JSON data without writing complex SQL.
Real Project Example
Suppose products store available sizes:
{"sizes": ["S","M","L","XL"]
}
Find all products available in Large size:
Product::whereJsonContains('sizes', 'L')->get();
Perfect for e-commerce filters.
Searching Multiple Values
Laravel can also match multiple values.
Product::whereJsonContains(
'sizes',
['M', 'L']
)->get();
This returns products containing both sizes.
Why Use whereJsonContains()?
It helps you:
- Query JSON arrays easily
- Avoid raw SQL
- Build dynamic filters
- Keep queries expressive
🧠When to Use It
Use whereJsonContains() when storing:
- User permissions
- Product attributes
- Languages
- Skills
- Tags
- Notification preferences