Posted by Arjun on Tuesday 24th February 2015

Using Query Scopes in Laravel?

Today i would like to write about Laravel Eloquent's Query Scopes , Query scopes are allow us to re-use query logic by allowing us to encapsulate database logic inside model class methods.

For example if you have a model called Posts.php, and if you have 3 type of post status fields called published,private,draft.

In general if you what to get all published posts you will write something like show below

//app/models/Posts.php
<?php
 
class Posts extends \Eloquent {
 
   public function getPublishedPosts()
    {
        return Posts::where(['status' => 'published'])->get();
    }

} 


	

Example:

//app/models/Posts.php
<?php
 
class Posts extends \Eloquent {

    public function scopePublished($query)
    {
       return $query->where(['status => 'published']);
    }
 
    public function getPosts()
    {
        return $this->published()->get();
    }

} 

How to pass parameters to scope

To pass parameters to scopes , just we need to pass second parameter to the scope method as shown below

//app/models/Posts.php
<?php
 
class Posts extends \Eloquent {

    public function scopePublished($query,$isActive)
    {
       return $query->where(['status => 'published','is_active' => $isActive]);
    }
 
    public function getPosts()
    {
        return $this->published(1)->get();
    }

} 

That's it.