Laravel Blade check user role

爷,独闯天下 提交于 2019-12-12 22:26:22

问题


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


回答1:


            @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)




回答2:


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


来源:https://stackoverflow.com/questions/37008388/laravel-blade-check-user-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!