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
1 2 3 4 5 6 7 8 9 10 11 |
//app/models/Posts.php <?php class Posts extends \Eloquent { public function getPublishedPosts() { return Posts::where(['status' => 'published'])->get(); } } |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//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.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.