Prefilter a Model table with current user

Published 1 week ago by gygabyte017

Hi have a classic user table (with id), and lots of Models linked to tables which have a column (id_user) matching the user id.

I would like, when I try e.g. to ->get(), to "automatically" filter each table and return only the rows where id_user is the current logged user id. Likewise, I'd like to "automatically" fill the field id_user with the current logged user id when I store a new record.

Is there a way to do this in a "smart" way?

Thanks

Best Answer (As Selected By gygabyte017)
TylerODonnell

Look into adding global query scopes and model events

use Illuminate\Database\Eloquent\Builder;

//

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

    // Retrieving
    static::addGlobalScope('logged_in_user', function (Builder $builder) {
        $builder->where('id_user', auth()->id);
    });

    // Saving
    static::creating(function ($model) {
        $model->id_user = auth()->id;
    });
}

Add this to a trait, or extend a base eloquent model for all the models you want this applied to.

TylerODonnell

Look into adding global query scopes and model events

use Illuminate\Database\Eloquent\Builder;

//

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

    // Retrieving
    static::addGlobalScope('logged_in_user', function (Builder $builder) {
        $builder->where('id_user', auth()->id);
    });

    // Saving
    static::creating(function ($model) {
        $model->id_user = auth()->id;
    });
}

Add this to a trait, or extend a base eloquent model for all the models you want this applied to.

gygabyte017

Thanks, that's amazing! Very clever indeed.

mmanieri

If the model is going to be used in contexts where no user is logged ("system" activities i.e. queued jobs, route model bindings for non auth'd routes) you might have unexpected results.

Might be useful to conditionally apply the scope when an auth'd user instance is actually available.

Sign In or create a forum account to participate in this discussion.