How to Use Query Scope in Laravel Eloquent

Published on March 21, 2020 37 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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

Author

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

Follow

Leave a Reply

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