How to Use Query Scopes With Laravel 5


If you are thinking to use Laravel query scope, this might be helpful for you.

Imagine that, you have a Post model, that you want access. In eloquent, you can access all the published post via-

$posts = Post::where('done', 1)->get();

Surely you will get all posts those are published.

Query Scope

Let's make query scope.

class Post extends Model
{

    public function scopeDone($query)
    {
        return $query->where('done', 1);
    }
}

Now, you are able to access this scope via-

$Post = Post::done()->get();

It will return all the published posts.

Query Scope in Dynamic Way

If you want to do query scope in dynamic way, here is the way.

class Post extends Model {
    public function scopeDone($query, $flag)
    {
        return $query->where('done', $flag);
    }
}

Now you can access like follows-

// Get Published Posts
$completedPosts = Post::done(true)->get();

// Get Unpublised Posts
$incompletePosts = Post::done(false)->get();

via Relationships

What if you think to apply in relationships? Well, here is the solution-

$user = User::find(1);
$completedPosts = $user->posts()->done(true)->get();

Have fun.