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??
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.
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');
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With