PHP

Define and Use Local Scopes in Laravel Eloquent

Learn to create and apply local query scopes in Laravel Eloquent models to encapsulate reusable query logic, making your code cleaner, more maintainable, and highly organized.

// In app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Scope a query to only include published posts.
     */
    public function scopePublished(Builder $query): void
    {
        $query->where('is_published', true)
              ->where('published_at', '<=', now());
    }

    /**
     * Scope a query to only include posts by a given user.
     */
    public function scopeByUser(Builder $query, int $userId): void
    {
        $query->where('user_id', $userId);
    }
}

// In a controller or route
use App\Models\Post;

// Get all published posts
$publishedPosts = Post::published()->get();
foreach ($publishedPosts as $post) {
    echo "Published Post: " . $post->title . "
";
}

// Get all published posts by a specific user (e.g., user ID 1)
$userPosts = Post::published()->byUser(1)->get();
foreach ($userPosts as $post) {
    echo "User 1's Published Post: " . $post->title . "
";
}
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse across your application. By prefixing a model method with `scope`, Eloquent automatically makes it available as a dynamic method on the model or query builder. This promotes the DRY principle, reduces code duplication, and makes your query logic much more readable and maintainable by abstracting complex conditions behind descriptive method names.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs