@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
For L5.3 the return line needs to change to the following:
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.