Query scopes are very funny and also powerful. I really like them because, like many programmers out there, I am absolutely and overwhelmingly lazy. I also have a great justification for my laziness: the Don't Repeat Yourself (DRY) principle.
In a few words, they let you reuse some logic in your queries. It is useful if you have similar queries in your application and you don't want to write them again and again every single time.
Let's take an example.
<?php // Book.php namespace App; class Book extends Model { public function scopeCheapButBig($query) { return $query->where('price', '<', 10)->where('pages_count', '>', 300); } }
What happened? I declared a scopeCheaperButBig
method. The scope
prefix is used to specify that this is going to be used as a scope.
Now, how can I use a scope?
Here it is:
<?php $bigAndCheaperBooks = \App\Book::cheapButBig()->get();
It is a cool feature. If you also think that you can split your...