Efficient Database Operations in Laravel with Model Scopes Global and Local Scopes Examples

Table of Contents

Laravel is a popular PHP framework that is widely used for web application development. One of the key features of Laravel is its ability to handle database operations efficiently. In this blog post, we’ll discuss model scopes in Laravel, which allow you to define pre-built query constraints that can be reused throughout your application.

Model Scopes in Laravel:

Model scopes are methods that can be defined on Eloquent models to provide pre-built query constraints. They are useful for defining frequently used query constraints that can be easily applied to any query on the model. Model scopes can be defined as global or local.

Global Scopes:

Global scopes are applied to all queries on a given model by default. They can be useful for applying constraints to all queries, such as filtering by a certain value or excluding soft-deleted records. To define a global scope, you can use the booted method on your model:

				
					class User extends Model
{
    protected static function booted()
    {
        static::addGlobalScope('active', function (Builder $builder) {
            $builder->where('active', true);
        });
    }
}
				
			

In this example, we define a global scope called “active” that filters records by the “active” column, which is assumed to be a boolean value. This scope will be applied to all queries on the User model by default.

Local Scopes:

Local scopes are applied to a specific query on a given model. They are useful for defining query constraints that are specific to a certain context, such as filtering by a specific date range or sorting by a certain column. To define a local scope, you can simply define a method on your model:

				
					class User extends Model
{
    public function scopeAdmins(Builder $query)
    {
        $query->where('is_admin', true);
    }
}
				
			

In this example, we define a local scope called “admins” that filters records by the “is_admin” column, which is assumed to be a boolean value. To apply this scope to a query, you can simply call the method on the query builder:

				
					$admins = User::admins()->get();
				
			

This will return all records where the “is_admin” column is true.

Example 1: Global Scope for Soft-Deleted Records:

A common use case for global scopes is to filter out soft-deleted records. Soft-deleting is a feature in Laravel where records are not physically deleted from the database but are instead marked as deleted by setting a “deleted_at” timestamp column to a non-null value. To filter out soft-deleted records, we can define a global scope on our model:

				
					class User extends Model
{
    protected static function booted()
    {
        static::addGlobalScope('not_deleted', function (Builder $builder) {
            $builder->whereNull('deleted_at');
        });
    }
}
				
			

In this example, we define a global scope called “not_deleted” that filters out records where the “deleted_at” column is not null. This scope will be applied to all queries on the User model by default.

Example 2: Local Scope for Filtering by Date Range:

A common use case for local scopes is to filter records by a specific date range. For example, suppose we have a “created_at” column on our User model and we want to filter records by a date range. We can define a local scope on our model to accomplish this:

				
					class User extends Model
{
    public function scopeCreatedBetween(Builder $query, $startDate, $endDate)
    {
        $query->whereBetween('created_at', [$startDate, $endDate]);
    }
}
				
			

In this example, we define a local scope called “createdBetween” that filters records by the “created_at” column between the given start and end dates. To apply this scope to a query, we can call the method on the query builder:

				
					$users = User::createdBetween('2022-01-01', '2022-12-31')->get();
				
			

This will return all records where the “created_at” column is between January 1st, 2022 and December 31st, 2022.

Conclusion:

Model scopes are a powerful feature in Laravel that allow you to define pre-built query constraints that can be reused throughout your application. Global scopes are applied to all queries on a given model by default and can be useful for applying constraints to all queries. Local scopes are applied to a specific query on a given model and are useful for defining query constraints that are specific to a certain context.

In this blog post, we discussed two examples of both global and local scopes. Global scopes can be used to filter out soft-deleted records, while local scopes can be used to filter records by a specific date range. By using model scopes, you can write more efficient and reusable queries in your Laravel application.

Popular Post

Leave a Reply

Your email address will not be published. Required fields are marked *