1

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?

6
  • if you remove @role('user-manager') hello @endrole will the error gone? Commented Mar 17, 2020 at 16:09
  • Yes, then it is gone Commented Mar 17, 2020 at 16:14
  • have you added added RoleServiceProvider in $providers array in config/app.php file? Commented Mar 17, 2020 at 16:23
  • Yes, when having a simple text in it, it is working. And when do dd($hasRole) it is returning true/false Commented Mar 17, 2020 at 16:36
  • I believe this directive is written incorrectly. Take a look at the generated view inside storage/framework/views (clear this directory first and then go to the page where you use this directive). You echo $hasRole but the view doesnt know that variable. Commented Mar 17, 2020 at 16:55

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Does this: return Auth::user()->hasRole($role); also work when using it inside a package and a custom User model?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.