Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

huug's avatar
Level 2

Multiple roles but shared models / controllers

So I'm building my first Laravel application and it's been quite a journey so far. I'm looking for some pointers to make sure I'm going about this the right way:

I have multiple roles in my application: superadmin, reseller, admin, supervisor and user

Where the superadmin can see/manage all users from all companies, the reseller only those belonging to companies under their account, the admin etc. can see users from their own account.

Right now I'm doing an if/else statement inside my UsersController, like this:

$users = (new User)->newQuery();

if( auth()->user()->hasRole('superadministrator') ) {
    // do nothing for now - show all users regardless
} elseif (auth()->user()->hasRole('reseller')) {
    $users->whereHas('company', function($q) {
        $q->where('reseller', auth()->user()->company_id);
    });
} else {
    $users->where('company_id', auth()->user()->company_id );
}

$users = $users->paginate(10);

Is this a good way of going about this? Or is this something that is better done by using scopes as the logic will be the same for practically every other object? What are pros and cons of different ways?

0 likes
3 replies
Shahrukh4's avatar

1). As for now you are building the query right.

2). It can be done by some other way or more laravel way as follows,

$users = User::query();

$query->when(auth()->user()->hasRole('reseller'), function($query){
    $query->whereHas('company', function($q) {
            $q->where('reseller', auth()->user()->company_id);
    });
})
->when(auth()->user()->hasRole('supervisor'), function($query){
    $query->where('company_id', auth()->user()->company_id );
});

$users = $query->paginate(10);

3). Or you can use Gates and Policies to restrict the view as per user roles, directly in your blades. Read the following referance for Gates and Policies. It is like more advance Laravel way to restrict views. Laravel Authorization

2 likes

Please or to participate in this conversation.