Policy in Laravel

  • Policies are classes that organize authorization logic around a particular model or resource.
  • For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts
  • Use policy when we want to group the auth logic of any model

Creating/Generating Policy

Generated using make:policy as

php artisan make:policy PostPolicy

To generate a class with basic CRUD policy methods we specify – -model as:

php artisan make:policy PostPolicy --model=Post

Registering Policy

No need to register if followed naming convention  (i.e. Auto Discover)

  1. Model is inside app
  2. policy name is equal to model name with suffix “Policy”

Register inside App\Providers\AuthServiceProvider.php as:

protected $policies = [

             Post::class => PostPolicy::class,

];

 

Writing Policy

Controller Method Policy Method
index viewAny
show view
create create
store create
edit update
update update
destroy delete
  • Writing policy means writing method inside generated policy
  • Above  table is auto generated default policy methods for model associated with it.

before() method

To execute before any other methods on policy

public function before($user, $ability) { if ($user->isSuperAdmin()) { return true; } }

Auth via. User Model  [ inside controller]

  • can
  • cant
if ($user->can('update', $post)) {
    //
}

use App\Post; if ($user->can('create', Post::class)) { // Executes the "create" method on the relevant policy... }

Auth via. Middleware

Route::put('/post/{post}', 'ControllerName@method')middleware('can:update,post');

Auth via. Controller

public function update(Request $request, Post $post) { $this->authorize('update', $post); // The current user can update the blog post... }

Auth via. Blade Template [ Resources ]

@can('update', $post)
    <!-- The Current User Can Update The Post -->
@elsecan('create', App\Post::class)
    <!-- The Current User Can Create New Post -->
@endcan

@cannot('update', $post)
    <!-- The Current User Cannot Update The Post -->
@elsecannot('create', App\Post::class)
    <!-- The Current User Cannot Create A New Post -->
@endcannot

 

// You may also determine if a user has any authorization ability from a given list of abilities. To accomplish this, use the @canany directive:

@canany(['update', 'view', 'delete'], $post)
    // The current user can update, view, or delete the post
@elsecanany(['create'], \App\Post::class)
    // The current user can create a post
@endcanany

 

Leave a Reply

Your email address will not be published. Required fields are marked *