ReFactor Default Query Scope in Laravel
Hello Artisans, today we'll talk about how to refactor our Laravel default query scope and how we can optimize our query by modifying the query scope. We all know to write queries using query scope and how we get rid of repeating the queries using query scope. So, we'll show how we can refactor and optimize that query scope.
At first we'll write a query scope which shows us a active user list:
public function scopeActive($query)
{
return $query->where('is_active',1);
}
And for fetching the list we used below query
App\Models\User::active()->get();
But we want to refactor this query. So, for that we've to create a class called UserQueryBuilder.php and paste the following code:
namespace App\Query;
use Illuminate\Database\Eloquent\Builder;
class UserQueryBuilder extends Builder
{
public function getActiveUserList() : self
{
return $this->where('is_active', 1);
}
}
And now we've to call this method through our User.php. See below
// first import our query builder class.
use App\Query\UserQueryBuilder;
// then paste this function
public function newEloquentBuilder($query) : UserQueryBuilder
{
return new UserQueryBuilder($query);
}
Now we can use the below query to fetch active users list:
App\Models\User::getActiveUserList()->get();
And we'll get the active user list by using our optimized code.
Hope this will help you write better and optimized queries. Thanks for reading. 🙂
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)