MODEL RETRIEVED EVENT METHOD OR GLOBAL SCOPE

May 03, 2024 Copy Link

I faced a scenario when I was working on a project where I had to replicate the `where` clause in many places and I was getting all the users in many end-points, then I realized that I should get the active users only, you may say Yeah, it's easy, you can walk through all the sections and update the query. Hmm, I think it's not the correct solution with Laravel

 

I did not completely know how I could use the retrieved event method, so when I used it, I found that it always gimme a single user instance, NOT a collection or a query builder instance; therefore, I can not control the triggered query, only you can change whatever user attribute:

 

/**
 * Bootstrap the model and its traits.
 */
public static function boot(): void
{
    parent::boot();

    static::retrieved(function ($user) {
        $user->name = 'New Name';
    });
}

 

Do not use any method of getting the data inside the `retrieved` closure or you will go into an infinite loop because it will call itself again and again.

 

From my point of view, the most practical solution is the Global Scope; therefore, I went to use it:

 

/**
 * Bootstrap the model and its traits.
 */
public static function boot(): void
{
    parent::boot();

    static::filterUsers();
}

/**
 * Get the active users.
 */
protected static function filterUsers(): void
{
    if (request()->is('/api/*')) {
        static::addGlobalScope('active', function ($builder) { 
             $builder->where('active', true); 
        });
    }
}

 

If you do not need to use the previous scope in a specific place you can use withoutGlobalScope.

Share via

Filed in:

Tips Eloquent
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autol...

    FREE

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE