How to Use Query Scope in Laravel Eloquent

We know that Laravel eloquent queries are the best ones. Today I’m going to share how to use query scope in Laravel eloquent. Let’s get started:

Table of Contents

  1. Create Scope
  2. Create Dynamic Scope
  3. Scope with Relation

Create Scope

Assume, we have a Model call Post. We’ll get all published posts from our database. Let’s do this using scope.

Open Post model and paste this code:

class Post extends Model
{

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

}

Laravel know scope as alias. We can get published posts using:

$publishedPosts = Post::published()->get();

Create Dynamic Scope

We can get data by passing parameter to the scope. This is called dynamic scope.

class Post extends Model
{

    public function scopePublished($query, $value)
    {
        return $query->where('published', $value);
    }

}

Now we can use it dynamically:

// published posts
$publishedPosts = Post::published(true)->get();

// unpublished posts
$unpublishedPosts = Post::published(false)->get();

Scope with Relation

We can also use the scope with eloquent relation.

$author= Author::find(1);
$publishedPostsOfAuthor = $author->posts()->published(true)->get();

That’s all. Thank you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.