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. 🙂