LoginSignup
1
0

More than 1 year has passed since last update.

【Laravel9】Policyを使って認可を与える

Last updated at Posted at 2022-06-27

Laravelで認可を与える方法

大きく2つの方法があり、Gateを使う方法とPolicyを使う方法がある。

Gate

特定のモデルに関連していないユーザーのアクションに関してアクセス制限を行う。

Policy

ある特定のモデルに対して行うアクションに関してアクセス制限を行う。
※今回はこちらのPolicyを使って行う

前提

  • Userモデル、Postモデルは既に作成している
  • laravel9

PostPolicyファイルを作成する

$ php artisan make:policy PostPolicy
Policy created successfully.

make:policyコマンドは、空のポリシークラスを生成する。
リソースの表示、作成、更新、削除に関連するポリシーメソッドのサンプルを含んだクラスを生成する場合は、
下記のようにコマンドの実行時に--modelオプションを指定する。

$ php artisan make:policy PostPolicy --model=Post
Policy created successfully.
namespace App\Policies;

use App\Models\User;
use App\Models\Post;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;
    
    /**
     * Determine whether the user can view any posts.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        //
    }

    /**
     * Determine whether the user can view the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function view(User $user, Post $post)
    {
        //
    }
   // 以下省略

Policyを利用してアクセス制限をかける準備をする

今回は投稿の編集を行うため、updateメソッドに記載をする。

class PostPolicy
{
    use HandlesAuthorization;

    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

作成したPolicyの情報をAuthServiceProvider.phpに登録する

作成したPolicyの情報はAuthServiceProvider.phpに登録を行う必要がある。
登録を行うことでPostモデルとPostPolicyが紐づけられる。

    protected $policies = [
        Post::class => PostPolicy::class,
    ];

authorizeメソッドを利用して制限をかける

authorizeメソッドを記述することでPolicyでアクセス制限を行うことができる。
updateメソッドに記載。

最初の引数(update)がPostPolicyファイル内に記述したupdateメソッドに対応する。
2番目の引数には、postモデルの変数$postを指定する。

public function update(Postrequest $request, $id) {

    $this->authorize('update', $post);
    $post->save();
    return view('posts.update');
}

viewにてcanを使ってログインユーザーのみに編集ボタンを出す

@can('update', $post)
    <td><a class="btn btn-info btn-sm" href="{{ url('posts/'.$post->id .'/' .'edit') }}">編集</a></td>
@endcan
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0