Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

How to Use Query Scope in Laravel Eloquent

Published on March 21, 2020 37 sec read

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. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *