Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

     

Laravel Gate Inspection

If you use Laravel gates and policies, chances are they look like this:

useIlluminate\Auth\Access\Response;classUserPolicy{useHandlesAuthorization;publicfunctionviewAny(User$user){if(!$user->hasRole('admin')){Response::deny("you must be admin to view the users");}returnResponse::allow();}}
Enter fullscreen modeExit 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 modeExit fullscreen mode

Read more about Gates and Responses inThe Laravel Doc

Just a bit further

You may want to add this to your AppServiceProvider as an helper for your Blade templates

classAppServiceProvider{publicfunctionboot(){Blade::directive('reason',function($expression){return"<?php echo Gate::inspect($expression)->message() ?>";});}}
Enter fullscreen modeExit 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 modeExit fullscreen mode

Which is slightly prettier.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I do all sorts of mischiefs with Laravel
  • Location
    Paris, France
  • Joined

More fromBenjamin Delespierre

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp