Search code examples
phplaravellaravel-bladeroles

Let button disappear when certain role is authenticated


I have two different tables where two different kind of users are stored.

The first are Portalusers, the second are employees.

Now I have an overview page of all posts, where Portalusers should be able to use a filter button for a department.

Employees should be able to use it aswell, IF their role IS NOT "FBL".

So I tried it with this code:

@if(auth()->user()->Rolle != 'FBL')
                <div class="text-left mb-4 h-12">
                    <select name="abteilung" id="abteilung" class="h-full w-full flex justify-center bg-white bg-opacity-95 rounded focus:ring-2 border border-gray-300 focus:border-indigo-500 text-base
                                outline-none text-gray-700 text-lg text-center leading-8">

                        <option selected="true" disabled="false">Abteilung</option>
                        @foreach($abteilungs as $abteilung)
                            <option value="{{ $abteilung->abteilung_name }}">{{ $abteilung->abteilung_name }}</option>
                        @endforeach
                        <option value="alle">Alle Abteilungen</option>
                    </select>
                </div>
                @endif

But when no-one is authenticated, so a guest is using the page I get an error Attempt to read property "Rolle" on null - which makes sense since no-one is authenticated.

But I also tried putting this before the @if:

@auth('web')
   @auth('portal')
      @auth('guest')

I have two guards, the one is the default laravel guard and the second one is my custom portalguard for portal users.

Is there any way I can make this work, so that the button is available when guests, portal users and employees which don't have the 'Rolle = FBL`, but disappears when someone with this specific role is logged in?


Solution

  • You need to check if user is logged in before trying to access the user object.

    To have it visible for guests and users with Rolle not as FBL, use this:

    @if( ! auth()->check() || auth()->user()->Rolle != 'FBL')
    

    https://laravel.com/docs/8.x/authentication#determining-if-the-current-user-is-authenticated