Skip to content

Using Query Scopes in Laravel?

Last updated on April 6, 2015

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
 'published'])->get();
    }

} 


	

Example:

//app/models/Posts.php
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
where(['status => 'published','is_active' => $isActive]);
    }
 
    public function getPosts()
    {
        return $this->published(1)->get();
    }

} 

That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments