Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LunaMooncraft's avatar

check multiple roles with Blade directive @can?

How can I achieve this:

@if (Auth::user()->role === 'admin' || Auth::user()->role === 'test')
	...
@endif

with the @can directive? Like:

@can ('admin' || 'test')
	...
@endcan
0 likes
4 replies
MichalOravec's avatar

Add this to AppServiceProvider

Blade::directive('hasrole', function ($arguments) {
    $roles = explode('|', $arguments);

    return "<?php if (auth()->check() && in_array(auth()->user()->role, {$roles})): ?>";
});

Blade::directive('endhasrole', function () {
    return '<?php endif; ?>';
});

Then you can use

@hasrole('admin|test')
    //
@endhasrole

Docs: https://laravel.com/docs/7.x/blade#extending-blade

Or you can use this package https://github.com/spatie/laravel-permission

4 likes
LunaMooncraft's avatar

thanks @michaloravec for introducing extending blade directives. That looks like a good alternative. My next step is to achieve multiple roles for one user. (if you have any tipps for this, feel free :) )

Few minutes ago, I tried with @canany and this works, too.

@canany(['admin', 'test'])
	...
@endcanany
5 likes

Please or to participate in this conversation.