Laravel Blade check user role
Asked Answered
R

3

9

In laravel Blade templating we can exclude some parts of HTML with this code:

        @if (Auth::user())
            <li><a href="{{ url('/home') }}">Mein Profil</a></li>
            <li><a href="{{ url('/admin') }}">Admin</a></li>
        @else
            <li><a href="{{ url('/home') }}">Mein Profil</a></li>
        @endif

If user is authenticated then show home and admin links and if user is not authenticated then show only home link.

My question is how to make a check here if user is admin?

I have default login system from laravel and i just added one more column in table users -> ('admin') with tinyint value 1 and in this video https://www.youtube.com/watch?v=tbNKRr97uVs i found the code for checking if user is admin

 if (!Auth::guest() && Auth::user()->admin )

and it works in AdminMiddleware.php but it doesn't work in blade. How to make this working??

Rihana answered 3/5, 2016 at 15:32 Comment(4)
Try to logout and login again, it may be because of you added column after loggedin and that may not be loaded ins Auth::user session. also add your dump response of this echo "<pre>"; print_r(Auth::user()); die() in your question, So we can see that admin column is coming or notFlaxseed
Are you getting any error?Reconstruct
I made a check route and with this it prints out check OK Route::get('check', function() { echo 'check OK'; }); and with this Route::get('check', function() { print_r(Auth::user()); }); prints nothing.....not even an error!Rihana
Sorry guys but it works now.....i think i needed just to reset the server :( my badRihana
M
14

I find such a long winded, check if logged in, check role, being added all around my blade files to distracting. You may consider adding a custom blade directive. Add something like this to AppServiceProvider boot() function

Blade::if('admin', function () {            
    return auth()?->user()?->admin === true;
});

in blade just use

@admin
<p>Only admin sees this</p>
@endadmin
Matteo answered 21/1, 2019 at 18:38 Comment(1)
Related: laravel.com/docs/9.x/blade#extending-bladeRance
R
4
            @if (!Auth::guest() && Auth::user()->admin)
                <li><a href="{{ url('/home') }}">Mein Profil</a></li>
                <li><a href="{{ url('/admin') }}">Admin</a></li>
            @else
                <li><a href="{{ url('/home') }}">Mein Profil</a></li>
            @endif      

this works just to be clear (just add one more column tinyint 'admin' in user table and set to 1)

Rihana answered 4/5, 2016 at 8:29 Comment(0)
S
4

You can use the method> HasRole

You can call this from artisan tinker from command line, just to see it before writing code:

php artisan tinker

Check if the user with id 1 has role 'user';

User::find(1)->hasRole('user');

Check if the user with id 1 has role 'admin';

User::find(1)->hasRole('admin');

The same way while coding for example in app.blade template:

@if (Auth::user()->hasRole('admin'))
        <li><a href="{{ url('/home') }}">Main Profile</a></li>
        <li><a href="{{ url('/admin') }}">Admin</a></li>
 @else
        <li><a href="{{ url('/home') }}">Main Profile</a></li>
 @endif

enter image description here

The method hasRoles comes from the package spatie/laravel-permission

composer.json: "spatie/laravel-permission": "^3.16"

enter image description here

full path of the class: vendor\spatie\laravel-permission\src\Traits\HasRoles.php

Sensual answered 24/8, 2022 at 14:48 Comment(2)
where does this method come from? ->hasRole() this seems not to be part of LaravelRihana
The method hasRole($roles, string $guard = null): bool --> is part of the vendor "spatie/laravel-permission" package. Full path: \vendor\spatie\laravel-permission\src\Traits\HasRoles.phpSensual

© 2022 - 2024 — McMap. All rights reserved.