Hello artisans,
Today I'll be writing about how to use Query Scopes efficiently in Laravel projects.
Query Scopes are very useful to encapsulate the logic you want to apply to database queries while using Models.
Let's start with an example and understand it step by step together.
Assume that there is a model called Post and we need to get only active posts. As you know it's simple and we only need to add a query condition to the Post model and get the results we needed. You can see the example below;
$activePosts = Post::where('is_active', '=', true)->get();
However, if we require to get active posts in multiple places that means we need to write the same code in multiple places too. Also, we might need to add some other conditions like getting posts published after a specific date and that means the code is going to be more complex over time.
How about making that much simpler and we can add the query conditions once needed simply by calling them?
Alright! That's possible because we can create simple Query Scope functions in the Post model and use them whenever we need them.
The following example shows how to create those two query scope functions that apply the query conditions we need to filter results.
class Post extends Model {
// applies active filter condition
public function scopeActive($query) {
$query->where('is_active', '=', 1);
}
// applies date filter condition
public function scopePublishedAfterDate($query, $date) {
$query->where('published_date', '>', $date);
}
}
Every Query Scope must be a function, starting with a scope keyword, and we need to place the name after the scope keyword.
Let's go back to the place where we needed to get only active posts and call the scope we needed to filter results.
$activePosts = Post::active()->get();
As you might notice the query scope function that we created to filter results to get only active posts from the database was called scopeActive but we used active instead because while calling query scope functions we must use the name defined after the scope keyword.
Now let's go back to the place where we need to get only active posts that are published after a date.
$activePosts = Post::active()->publishedAfterDate('2024-04-01')->get();
And simple that will also work.
That's all for Query Scopes in Laravel, if you need to ask anything just send me a message on Twitter.