Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Blade check user role

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??

like image 617
lewis4u Avatar asked May 03 '16 15:05

lewis4u


People also ask

How do I check permissions in laravel blade?

Instead, use Laravel's native @can directive to check if a user has a certain permission. You can use @can , @cannot , @canany , and @guest to test for permission-related access.

How can I check my role in Spatie laravel?

You can determine if a user has a certain role: $user->hasRole('writer'); // or at least one role from an array of roles: $user->hasRole(['editor', 'moderator']); You can also determine if a user has any of a given list of roles: $user->hasAnyRole(['writer', 'reader']); // or $user->hasAnyRole('writer', 'reader');

How do I assign a role in laravel?

To get started with adding our roles and permissions to our Laravel application, we'll need to first store them in the database. It's simple to create a new role or permission because, in Spatie's package, they're just models: Spatie\Permission\Models\Role and Spatie\Permission\Models\Permission .


1 Answers

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 () {            
            if (auth()->user() && auth()->user()->admin) {
                return 1;
            }
            return 0;
        });

in blade just use

@admin
<p>Only admin sees this</p>
@endadmin
like image 124
ravenshill Avatar answered Sep 30 '22 13:09

ravenshill