Laravel Blade check user role

2019-08-03 05:08发布

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

2条回答
戒情不戒烟
2楼-- · 2019-08-03 05:20
            @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 cleared (just add one more column tinyint 'admin' in user table and set to 1)

查看更多
虎瘦雄心在
3楼-- · 2019-08-03 05:32

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
查看更多
登录 后发表回答