DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

4

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay