OctoberCMS / Anonymous Global Scope

227 Views Asked by At

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);
      });
    }
2

There are 2 best solutions below

0
Pettis Brandon On BEST ANSWER

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();
0
Sam On

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);
  });
}