PHP

Create Reusable Eloquent Queries with Local Scopes

Enhance code reusability and maintainability in Laravel by defining local query scopes, allowing you to encapsulate common query constraints.

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

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Scope a query to only include active posts.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'published');
    }

    /**
     * Scope a query to only include posts by a given user.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $userId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}

// Usage in controller or elsewhere
$activePosts = App\Models\Post::active()->get();

$userPosts = App\Models\Post::byUser(123)->active()->get();

$recentActivePosts = App\Models\Post::active()->orderBy('created_at', 'desc')->take(5)->get();
How it works: Local query scopes allow you to define common sets of query constraints that can be easily reused throughout your application. By prefixing a method in your model with `scope` (e.g., `scopeActive`), it becomes available as a method on the Eloquent model or query builder (e.g., `Post::active()`). This promotes cleaner, more readable code, reduces duplication, and makes your queries more maintainable, especially for complex or frequently used conditions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs