You need to put all the logic in the output code because the view is built in advance of variable data.
So your evaluation of the user permission needs to be expressed in code that you echo into the view.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi all, I was wondering if someone could provide some help... I'm trying to setup a Blade directive but been stuck on it for some time now... Here's what I have so far:
Blade::directive('hasPermission', function ($expression) {
list($user, $permission) = explode(', ', $expression);
$permissions = "<?= with{$user}->permissions ?>";
$hasPermission = in_array($permission, $permissions) ? 'true' : 'false';
return "<?php if ($hasPermission): ?>";
});
I am expanding functionality upon this: https://github.com/laracasts/roles-and-abilities
Watched tutorial: https://laracasts.com/series/intermediate-laravel/episodes/12
$user and $permission are still being treated as strings.
I started a new project to try and get your Blade directive to work, and this seems to work perfectly.
// In view
// It also works with Auth::user()
@hasPermission(auth()->user(), 'view_bookings')
Yes !
@endif
// In AppServiceProvider.php
Blade::directive('hasPermission', function ($expression) {
list($user, $permission) = explode(', ', $expression);
return "<?php if (in_array($permission, ($user)->permissions ?? [])): ?>";
});
Two things :
null
php artisan view:clear after changing your Blade directive's codeYou could also add a little touch to be less restrictive regarding the exact formatting of your parameters. With the current code, you will receive an error if there's no space or more than 1 space between your comma and your second parameter. To resolve the issue, you could explode the comma only and use trim to remove the excess spaces.
Blade::directive('hasPermission', function ($expression) {
list($user, $permission) = explode(',', $expression);
$user = trim($user);
$permission = trim($permission);
return "<?php if (in_array($permission, ($user)->permissions ?? [])): ?>";
});
Please or to participate in this conversation.