Advertisement
wpshagor

Laravel Authorization with Gates

Jan 24th, 2020
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. ### Laravel Authorization with Gates
  2.  
  3. Step-1: Define authorization in AuthServiceProvider.php
  4.  
  5. Gate::define('update-post', function ($user, $post) {
  6. return $user->id == $post->user_id;
  7. });
  8.  
  9. here, 'update-post' is the name of action, and $post is the model instance
  10.  
  11. Step-2: To authorize an action using gates, you should use the allows or denies methods in controller function for view or edit.
  12.  
  13.  
  14. if (Gate::allows('edit-settings')) {
  15. // The current user can edit settings
  16. }
  17.  
  18. Step-3: Authorize action button on view file (Blade).
  19.  
  20. 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:
  21.  
  22.  
  23. @can('update', $post)
  24. <!-- The Current User Can Update The Post -->
  25. @elsecan('create', App\Post::class)
  26. <!-- The Current User Can Create New Post -->
  27. @endcan
  28.  
  29.  
  30. We can also writing if else like this--
  31.  
  32. @if (Auth::user()->can('update', $post))
  33. <!-- The Current User Can Update The Post -->
  34. @endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement