If you use Laravel gates and policies, chances are they look like this:
use Illuminate\Auth\Access\Response;
class UserPolicy
{
use HandlesAuthorization;
public function viewAny(User $user)
{
if (! $user->hasRole('admin')) {
Response::deny("you must be admin to view the users");
}
return Response::allow();
}
}
If so, instead of hiding links and button in your views via @can and @cannot , you may want to display a message instead.
To do so, you can simply inspect the gate:
@can('viewAny', User::class)
<a href="{{ route('app.user.index') }}">User Index</a>
@else
You cannot index users because {{ Gate::inspect('viewAny', User::class)->message() }}
@cannot
Read more about Gates and Responses in The Laravel Doc
Just a bit further
You may want to add this to your AppServiceProvider as an helper for your Blade templates
class AppServiceProvider
{
public function boot()
{
Blade::directive('reason', function ($expression) {
return "<?php echo Gate::inspect($expression)->message() ?>";
});
}
}
And use it like this:
@can('viewAny', User::class)
<a href="{{ route('app.user.index') }}">User Index</a>
@else
You cannot index users because @reason('viewAny', User::class) }}
@cannot
Which is slightly prettier.
Top comments (0)