PHP
Create Reusable Query Segments with Eloquent Local Scopes
Discover how to define reusable query constraints directly within your Eloquent models using local scopes, making your code cleaner and more modular.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Define a local scope for published posts
public function scopePublished($query)
{
return $query->where('published_at', '<=', now())
->where('is_draft', false);
}
// Define a local scope for searching posts by title or body
public function scopeSearch($query, $searchTerm)
{
return $query->where('title', 'like', '%' . $searchTerm . '%')
->orWhere('body', 'like', '%' . $searchTerm . '%');
}
}
// Usage:
// $publishedPosts = Post::published()->get();
// $searchResults = Post::published()->search('eloquent tips')->get();
How it works: Local scopes are methods defined on an Eloquent model that begin with 'scope'. They allow you to encapsulate common sets of query constraints, making your controller or service code much cleaner and more readable. You can chain multiple local scopes and other query methods together, providing flexible and modular ways to build complex queries.