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

marcellopato's avatar

Laratrust roles and permisions

Greetings from Brasil!

That's the way I found to create users as administrator and lower levels of roles. I know that there is a better and more clever way. Could anyone help me?

Let's see some code:

public function create()
    {
        if (Laratrust::hasRole('administrator')) {
            $roles = Role::where('id','>', 1)->get();
            return view('layouts.usuarios.create')->withRoles($roles);
        } else {
            $roles = Role::all();
            return view('layouts.usuarios.create')->withRoles($roles);
        }
    }

As doing that, the role loop doesn't show the superadministrator one. How can I make this more efficient and dynamic?

0 likes
5 replies
rawilk's avatar
rawilk
Best Answer
Level 47

I'd make it a query scope like this on the role model:

public function scopeGetAllowed($query)
{
    if (Laratrust::hasRole('administrator')) {
        $query->where('id', '>', 1);
    }

    return $query;
}

Then in your controller, you'd do this:

public function create()
{
    $roles = Role::getAllowed()->get();
    return view('layouts.usuarios.create')->withRoles($roles);
}
2 likes
marcellopato's avatar

Let's say I am an administrator and want to list all user, BUT the superadministrator.

I'm trying something like this:

public function index()
    {
        if(Laratrust::hasRole('superadministrator')) {
            $usuarios = User::all();
            return view('layouts.usuarios.index')->withUsuarios($usuarios);
        } elseif (Laratrust::hasRole('administrator')){
            $usuarios = User::whereRoleIs('administrator','usuario','cliente')->get();
            return view('layouts.usuarios.index')->withUsuarios($usuarios);
        }
    }

... and of course, with no success.

rawilk's avatar

Can you show me the whereRoleIs?

Also, for this, I'd also make a query scope on the User model similar to what I showed you earlier with the Roles.

1 like

Please or to participate in this conversation.