PHP
Creating Reusable Local Query Scopes in Laravel Eloquent
Discover how to define local query scopes in Laravel Eloquent to encapsulate common sets of query constraints, making your code cleaner, more readable, and highly reusable across your application.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
/**
* Scope a query to only include active products.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('status', 'active');
}
/**
* Scope a query to only include products in a given category.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $category
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCategory($query, $category)
{
return $query->where('category_id', function ($subQuery) use ($category) {
$subQuery->select('id')
->from('categories')
->where('name', $category);
});
}
// Usage examples:
// $activeProducts = Product::active()->get();
// $electronics = Product::category('Electronics')->active()->get();
}
How it works: Local query scopes allow you to define common sets of query constraints that can be easily reused across your application. By defining methods prefixed with `scope` on your Eloquent models, you can chain these scopes onto your queries, leading to more readable and maintainable code. This approach promotes the DRY (Don't Repeat Yourself) principle by centralizing query logic.