ホーム > Laravel > How to Authorize with Laravel Policy
Laravel

How to Authorize with Laravel Policy

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents of Laravel articles

When trying to use Policy for authorization, I made a mistake in the steps and received an error message like this:

Argument 2 passed to App\Policies\PostPolicy::Post() must be an instance of App\Post, string given, called in /vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 198 {"userId":1,"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0):

I didn't want to waste time with such errors again, so I summarized the steps on how to authorize using Laravel Policy.

What is Authorization?

It is verifying whether the person has the permission to do it.

Difference from Authentication

Authentication identifies "who this person is", while authorization determines whether that person has the permission or not.

In Laravel, you can implement authorization using Policy.

Steps to Use Policy

This time, let's check if a user has the permission to edit a post.

Creating a Policy file with Command

php artisan make:policy PostPolicy

Writing in PostPolicy file

<?php

namespace App\Policies;

use App\Post;
use App\User;

class PostPolicy
{
//User is the authenticated model
//Post is the model we want to use for authorization this time
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

Writing in AuthServiceProvider

AuthServiceProvider is located in App/Providers/AuthServiceProvider.php.

Add this inside the boot function.

    public function boot()
    {
      $this->registerPolicies();
      //Add the following
      Gate::define('update-post','App\Policies\PostPolicy@update');
    }

web.php

Add middleware to the route so that unauthorized users cannot call the Controller.

I like this method because it makes the groups clear.

Route::group('middleware' => ['auth','can:update-post,post']], function () {
  Route::post('post/update/{post}',"PostController@update");
});

①The part with can:update-post will contain the content defined in AuthServiceProvider.

②Be careful not to forget the post argument in "can:update-post,post"

③The postId will be included in the URL parameter.

post/update/{post}⇦ Essentially, postId will be included.

PostController

use App\Post;

public function update(Post $post)
{

}

Be careful not to forget Post $post.

Successful result: 403 Error

If you try to modify a post created by someone else, you will receive a "403 (Forbidden)" error.

Summary

Since writing Policies can be occasional, I have summarized the steps.

For complaints or opinions, please contact me via Twitter DM.

That's all!

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!