DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

Laravel Gate Inspection

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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() ?>";
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Which is slightly prettier.

Top comments (0)