Roles and Permissions - Step 6 - Using Roles to Control what the User Sees on Login

Once you get your permissions set up and working you can use the Laravel @can directive to check whether a user, once logged in, has permission to access a certain page or area of the site. If they don't have permission they can be given an error and re-directed.

In addition to this Spatie adds a range of directives relating to Roles. These can also be very handy and, if you wish, be used to show additional menu options or even completely different pages/look and fee.

In the last post we locked down the system so that only the System Admin could access routes relating to Roles, Permissions and Users. To knit this into our UI it would be nice if there was an additional Navbar dropdown menu which could access these routes. Ideally, this Navbar menu will only appear if the user is logged in as a System Admin. To create this sub navbar save the following code into a file called \resources\views\layouts\adminmenu.blade.php.

<li class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">Admin Menu
    <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
             <a href="{!! route('users.index') !!}">Users</a>
        </li>
        <li>
             <a href="{!! route('roles.index') !!}">Roles</a>
        </li>
        <li>
             <a href="{!! route('permissions.index') !!}">Permissions</a>
        </li>
    </ul>
</li>

Now edit your top level view \resources\views\layouts\app.blade.php and place the following HTML code into your navbar

<ul class="nav navbar-nav navbar-right" style="margin-right:10px">
     @if(Auth::check())
         @if(Auth::user()->hasRole('System Admin'))
             @include('layouts.adminmenu')
         @endif 
         <li><a href="{!! route('logout') !!}"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
     @else
         <li><a href="{!! route('login') !!}"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
         <li><a href="{!! route('register') !!}"><span class="glyphicon glyphicon-user"></span> Register</a></li>
     @endif
 </ul>

If you followed the posts at the beginning of the security section you will already have a "navbar-right" list in your navbar for the user login and logout. I'm including this full block of code here just in case. This is what it looks like in my navbar overall.

To get a dropdown navbar to work for bootstrap you need to make sure you have the javascript/jquery elements of bootstrap working. You may need to add the following lines to the header section of the page in layouts\app.blade.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Now, if I view the any of the pages when logged in as a System Admin I get an additional Admin navbar

Leave a Reply