Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Laravel Authorization with Gates
- Step-1: Define authorization in AuthServiceProvider.php
- Gate::define('update-post', function ($user, $post) {
- return $user->id == $post->user_id;
- });
- here, 'update-post' is the name of action, and $post is the model instance
- Step-2: To authorize an action using gates, you should use the allows or denies methods in controller function for view or edit.
- if (Gate::allows('edit-settings')) {
- // The current user can edit settings
- }
- Step-3: Authorize action button on view file (Blade).
- We can display a portion of the page only if the user is authorized to perform a given action. For example, you may wish to show an update form for a blog post only if the user can actually update the post. In this situation, you may use the @can and @cannot family of directives:
- @can('update', $post)
- <!-- The Current User Can Update The Post -->
- @elsecan('create', App\Post::class)
- <!-- The Current User Can Create New Post -->
- @endcan
- We can also writing if else like this--
- @if (Auth::user()->can('update', $post))
- <!-- The Current User Can Update The Post -->
- @endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement