'OctoberCMS / Anonymous Global Scope

I am use OctoberCMS Rainlab.User plugin to manage authentication.

I have various models and that belongTo User.

How do i set up an anonymous global scope on each model to only return the records that belong to the authenticated user?

Many thanks in advance for any help.

use Auth;

protected static function booted()
    {
        $user = Auth::getUser();
        static::addGlobalScope('user_id', function (Builder $builder){
        $builder->where('user_id', $user);
      });
    }


Solution 1:[1]

I would create a dynamic scope in the model's definition page. You can read more about it here.

class PluginModel extends Model
{
    /**
     * Scope a query to only records with user.
     */
    public function scopeGetUserRecords($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}

Now any time you call your PluginModel class you can just do this:

$userRecords = PluginModel::getUserRecords($user->id)->get();

Solution 2:[2]

It's fairly similar to how you do it in straight laravel as you already tried to do. You just add it to the model's boot function instead of booted.

protected static function boot()
{
  parent::boot();

  $user = Auth::getUser();
  static::addGlobalScope('user', function ($query) use ($user) {
    $query->where('user_id', $user->id);
  });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pettis Brandon
Solution 2 Sam