Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel Global Scope Example

Laravel Global Scope Example

Global scope in Laravel: In this tutorial, you will learn in detail what global scopes are, and how to create/define and use them with relationships in Laravel 10, 9, and 8 applications

Global Scopes are a powerful tool that can help you to enforce business rules, filter data, or apply some other custom logic across all queries for a given model in laravel. With Global Scopes, you can define constraints that will be applied to every query for a model, without having to repeat the same code in every query.

Global Scope In Laravel

Here is an explanation of global scope; is as follows:

  • What is a Laravel Global Scope?
  • How to Define a Global Scope in Laravel?
  • How to Use a Global Scope in Laravel?
  • Define a Global Scope Relationship in Laravel

What is a Laravel Global Scope?

A global scope in Laravel is a way to apply certain conditions to all queries made against a particular database model. For example, you might have a requirement to filter out any records from a database table that have been soft-deleted. Rather than including this condition in every query, you can define a global scope that automatically applies this condition to all queries made against the model.

Global scopes are defined using the boot method in your model class. This method is called when your application boots up and allows you to modify the model’s behavior before any queries are executed. You can define as many global scopes as you like for a given model, and they can be combined with other query conditions to create complex queries.

How to Define a Global Scope in Laravel?

Defining a global scope in Laravel is straightforward. To define a global scope, you need to create a new class that extends the Laravel’s Illuminate\Database\Eloquent\Scope class and implements the apply() method.

The apply() method is where you define the constraint that you want to apply to the queries. This method receives two arguments: the Builder instance and the Model instance. The Builder instance represents the query builder instance, and the Model instance represents the model instance.

Here is an example of a global scope that adds a default ordering to all queries executed on a model:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class OrderByScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->orderBy('created_at', 'desc');
    }
}

In this example, To define a OrderByScope class that implements the Scope interface. The apply() method adds a default ordering to all queries executed on the model by ordering the records by their created_at column in descending order.

How to Use a Global Scope in Laravel?

To use a global scope in Laravel, you need to register the scope with the model. This is done by defining a booted() method on the model and calling the addGlobalScope() method.

Here is an example of how to register the OrderByScope global scope with a model:

<?php

namespace App\Models;

use App\Scopes\OrderByScope;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new OrderByScope);
    }
}

In this example, to define a Post model that extends the Laravel’s Illuminate\Database\Eloquent\Model class. To register the OrderByScope global scope by calling the addGlobalScope() method in the booted() method of the model.

Now, when you execute a query on the Post model, the global scope will be applied, and the records will be ordered by their created_at column in descending order.

Define a Global Scope Relationship in Laravel

Defining a global scope relationship in Laravel is similar to defining a global scope on a model. To define a global scope relationship, you need to create a new class that extends the Laravel’s Illuminate\Database\Eloquent\Scope class and implements the apply() method.

Here is an example of a global scope relationship that adds a default ordering to all queries executed on a model’s relationship:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class OrderByScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->orderBy('created_at', 'desc');
    }
}

In this example, to define a OrderByScope class that implements the Scope interface. The apply() method adds a default ordering to all queries executed on a model’s relationship by ordering the related records by their created_at column in descending order.

To use a global scope relationship in Laravel, you need to register the scope with the relationship. This is done by defining a booted() method on the model and calling the addGlobalScope() method with the relationship name as the first argument.

Here is an example of how to register the OrderByScope global scope relationship with a model’s relationship:

<?php

namespace App\Models;

use App\Scopes\OrderByScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    protected static function booted()
    {
        static::retrieved(function ($user) {
            $user->posts->addGlobalScope(new OrderByScope);
        });
    }
}

In this example, To define a User model that has a one-to-many relationship with a Post model. To register the OrderByScope global scope relationship by calling the addGlobalScope() method on the posts relationship in the retrieved() event of the model.

Now, when retrieve a user and access their posts relationship, the global scope relationship will be applied, and the related records will be ordered by their created_at column in descending order.

Conclusion

Laravel global scopes relationships are a powerful feature that allows you to add constraints to all queries executed on a model’s relationship. Global scopes relationships can be used to add default orderings, filter out soft-deleted records, or add additional conditions to a query.

In this article, You have learned how to define and use a global scope relationship in Laravel. By following the steps outlined in this article, you can easily add global scopes relationships to your Laravel models and take advantage of the benefits they offer.

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments