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


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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();

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x