xhulio
xhulio

Reputation: 1103

displaying navbar according to user roles and permisions laravel

I am implementing user roles in laravel 5 and I want to update the navbar according to the user permissions. The default navbar has A, B, and C menus which redirect to the specific pages. Let's say that user 1 can view page A and B, while user 2 can view only C. When user 1 logs in, I want the navbar to show only A and B menus. I want to do this in a single page and don't want to create a master page for every user role (as was suggested to me). Any help or hint is appreciated.

Upvotes: 1

Views: 3743

Answers (1)

haakym
haakym

Reputation: 12358

Firstly you need to explain how your roles are set up in your system. So consider that the following example has some assumptions...

If for example your User model has a relationship to a Roles model, as so:

public function roles()
{
    return $this->belongsToMany('\App\Role');
}

You can then add a method to your User model to check if a User has a certain role:

public function hasRole($name)
{
    foreach ($this->roles as $role) 
    {
        if ($role->name == $name) return true;
    }

    return false;
}

You can then do something like this in your nav view (using blade)

@if (Auth::user()->hasRole('admin'))
  <!-- nav links here -->           
@endif

Upvotes: 3

Related Questions