Zelda Taylor
Zelda Taylor

Reputation: 5

Passing an array to Laravel Blade Directive

I am trying to avoid doing the following in blade

<?php if(auth()->check() && auth()->user()->hasRoles(['administrator', 'superadmin'])) { ?>
...
<?php } ?>

I tried a blade directive like this;

Blade::directive('roles', function ($roles) {
        return "<?php if (auth()->check() && auth()->user()->hasRoles({$roles}): ?>";
    });

I get this error:

syntax error, unexpected ':' (View: /Users/.../index.blade.php)

When I try this in laravel blade;

@roles(['admin', 'super-admin'])
...
@endroles

I want to pass an array of roles in blade and have the right permissions executed. I do have a method on the User model called hasRoles(array $roles) that accepts an array of roles.

Upvotes: 0

Views: 608

Answers (1)

Digvijay
Digvijay

Reputation: 8957

There a ':' at the end of your if condition

if (auth()->check() && auth()->user()->hasRoles({$roles}):

change it to

if ( auth()->check() && auth()->user()->hasRoles({$roles}) ) { ... }

Upvotes: 0

Related Questions