Laravel Query Scopes Example

Laravel query scopes; In this tutorial, we are going to show you what is query scope in laravel and how to create & use query scopes with relationships, joins, methods and parameters in laravel 10, 9, 8 apps.

In Laravel, query scopes are a powerful feature that allows developers to define reusable sets of constraints for database queries. Query scopes are essentially pre-built queries that can be used across multiple models and can help to keep your code DRY (Don’t Repeat Yourself).

In this article, we will explore the concept of query scopes in Laravel and look at an example of how to use them.

Laravel Query Scopes

In this tutorial you will learn what is query scope in laravel and how to create query scope. as well as how to use it with relationships, joins, methods & paramaters:

  • What are Query Scopes?
  • Creating a Query Scope in Laravel
  • Using a Query Scope in Laravel
  • Using Query Scopes with Relationships
  • Using Query Scopes with Joins

What are Query Scopes?

Query scopes are methods on Laravel’s Eloquent models that can be used to add constraints to a query. These methods are similar to Laravel’s global query scope, but they can be defined on a per-model basis and can be chained with other query builder methods. When called on a model, a query scope will add a set of constraints to the query, such as a where clause, and return the modified query builder instance.

Query scopes are useful for several reasons. They can help to reduce code repetition by allowing you to define complex queries in one place and use them across multiple models. They can also make your code more readable and maintainable by encapsulating complex query logic in a single method.

Creating a Query Scope in Laravel

To create a query scope in Laravel, we need to define a method on the Eloquent model that we want to add the scope to. The method should return a query builder instance, and it can accept parameters that modify the behavior of the scope.

Here’s an example of a query scope that adds a where clause to a query to filter by a specific status:

class Task extends Model
{
    public function scopeStatus($query, $status)
    {
        return $query->where('status', $status);
    }
}

In this example, we’re defining a query scope called ‘status’ on the Task model. The scope takes a single parameter, $status, which is used to filter tasks by their status. When called on a Task model instance, the scope will add a where clause to the query to filter by the given status.

Using a Query Scope in Laravel

Once we have defined a query scope on a model, we can use it like any other query builder method. Here’s an example of how to use the ‘status’ scope defined above:

$tasks = Task::status('complete')->get();

In this example, we’re calling the ‘status’ scope on the Task model to retrieve all tasks with a status of ‘complete’. The scope adds a where clause to the query to filter by the status, and the resulting collection of Task objects is returned.

We can also chain multiple query scopes together to create more complex queries. Here’s an example:

$tasks = Task::status('complete')
             ->orderBy('created_at', 'desc')
             ->limit(10)
             ->get();

In this example, we’re chaining three query scopes together: ‘status’, ‘orderBy’, and ‘limit’. The resulting query will retrieve the 10 most recently created tasks with a status of ‘complete’, ordered by their creation date in descending order.

Using Query Scopes with Relationships

Laravel’s query scopes can also be used with model relationships to filter results based on related models. For example, suppose we have a “Post” model that has a “hasMany” relationship with a “Comment” model. We can define a query scope on the “Post” model that retrieves only posts that have comments:

public function scopeHasComments($query)
{
    return $query->whereHas('comments');
}

This query scope can be used like this:

$posts = Post::hasComments()->get();

This will retrieve all posts that have comments associated with them.

Using Query Scopes with Joins

Laravel’s query scopes can also be used with database joins to retrieve data from multiple tables. Suppose we have a “User” model that has a “hasMany” relationship with a “Post” model, and we want to retrieve all users who have posted in the last 30 days. We can define a query scope on the “User” model that joins the “posts” table and adds a constraint on the “created_at” column:

public function scopeActiveInLast30Days($query)
{
    return $query->join('posts', 'users.id', '=', 'posts.user_id')
                 ->where('posts.created_at', '>=', Carbon::now()->subDays(30))
                 ->groupBy('users.id');
}

This query scope can be used like this:

$users = User::activeInLast30Days()->get();

This will retrieve all users who have posted in the last 30 days.

Conclusion

Query scopes are a powerful feature in Laravel that can help to keep your code DRY and make it more readable and maintainable. By defining reusable sets of constraints on database queries, you can save time and effort when working with complex database queries across multiple models. So next time you find yourself writing the same query over and over again, consider creating a query scope instead!

More Tutorials

Leave a Comment