php – Custom Laravel Blade Directive gives error when if statement is being used-ThrowExceptions

Exception or error:

I have this opiece of code in the boot of my RoleServiceProvider:

public function boot()
{
    Blade::directive('role', function ($role) {

        $hasRole = User::find(Auth::id())->hasRole($role);

        return "<?php if ( $hasRole  ) : ?>";
    });

    Blade::directive('endrole', function ($role) {
       return "<?php endif; ?>";
    });
}

The var $hasRole is holding the status: true/false, now i my blade:

@role('user-manager')
    hello
@endrole

Looks OK to me, but it is giving me this error:

Facade\Ignition\Exceptions\ViewException
syntax error, unexpected ‘)’ (View: C:\wamp64\www\laravel6\packages\users\management\src\View\overview.blade.php)

For some reason I don’t know as the code looks fine to me..
Some suggestions?

How to solve:

Try to use if directive instead.

Blade::if('role', function ($role) {
    return User::find(Auth::id())->hasRole($role);
});

In Blade:

@role('user-manager')
  hello
@endrole

Also, you can get a user object straight away from Auth like this:

return Auth::user()->hasRole($role);

Leave a Reply

Your email address will not be published. Required fields are marked *