Skip to content

Instantly share code, notes, and snippets.

@dillinghamio
Last active April 20, 2021 00:39
Show Gist options
  • Save dillinghamio/080313d699b56ebf44e1fa3b59ea6f9b to your computer and use it in GitHub Desktop.
Save dillinghamio/080313d699b56ebf44e1fa3b59ea6f9b to your computer and use it in GitHub Desktop.
@ROLE Blade Directive For Laravel Spark

@role Blade Directive For Laravel Spark

Assumes you're using teams

Add this to the boot() method of your AppServiceProvider

\Blade::directive('role', function($roles) {

        $user = auth()->user();

        $userRole = $user->roleOn($user->currentTeam);

        return "<?php if((is_array(with{$roles})) ? in_array('$userRole', with{$roles}) : with{$roles} == '$userRole') : ?>";
});

\Blade::directive('endrole', function() {

        return "<?php endif; ?>";
});

And use like so

@role('owner')
    <h1>Owner</h1>
@endrole

@role('member')
    <h1>Member</h1>
@endrole

Can also pass an array of multiple roles

@role(['member', 'owner'])
    <h1>Member or Owner</h1>
@endrole

See also @plan Blade Directive For Laravel Spark

@jpmurray
Copy link

jpmurray commented May 9, 2016

@dillinghamio that's great for the array! I tried myself with the in_array() method and couldn't get it to work ;-) I love your solution better!

@nateritter
Copy link

nateritter commented Sep 10, 2016

For L5.3 the return line needs to change to the following:

return "<?php if((is_array(with({$roles}))) ? in_array('$userRole', with({$roles})) : with({$roles}) == '$userRole') : ?>";

And in case anyone is wondering why they probably aren't seeing what they would expect when they switch users to one of a different role (i.e., masquerading or "becoming" another user, tests failing randomly, etc), it's because custom directives are cached and since there's a conditional involved in the directive, you'll have to php artisan view:clear it somehow. This means although the directive is great, it may not be the best choice of implementation depending on what you're trying to accomplish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment