0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LaravelのGate(ゲート)、Policy(ポリシー)について

Posted at

Gate(ゲート)、Policy(ポリシー)について

  • Gate
    簡単に特定の動作に制限をかけたいとき

  • Policy
    モデルごと、リソースコントローラーごとなどまとめて制限をかけたいとき

Gate(ゲート)

Gateの設定方法

認可(Authorization)を制御するための機能で、特定のアクションをユーザーが実行できるかを判断する際に使う。

App\Providers\AuthServiceProvider の boot メソッド内で定義する。

//Gateファサードを読み込む
use Illuminate\Support\Facades\Gate;
//認可処理で使うユーザーモデル(App\Models\User)をインポート
use App\Models\User;

//update-post という認可ルールの名前(キー)を定義
//$user: 認証済みユーザー
//$post: 認可を確認したいリソース(投稿)
//投稿の user_id が現在ログインしているユーザーの id と一致するか
public function boot()
{
    Gate::define('update-post', function (User $user, \App\Models\Post $post) {
        return $user->id === $post->user_id;
    });
}

Bladeテンプレートで使用する場合

@can('update-post', $post)
    <a href="{{ route('posts.edit', $post) }}">編集</a>
@endcan

コントローラーで使用する場合

if (Gate::allows('update-post', $post)) {
    // 更新処理
}

Policy(ポリシー)

Policyの設定方法

あるモデルに対する認可ロジック(誰が何をしてよいか)をクラス単位で管理する。

①まずは下記コマンドで、新規Policyを作成する。

php artisan make:policy PostPolicy --model=Post

②PostPolicyに下記ロジックを追加する。

namespace App\Policies;

use App\Models\User;
use App\Models\Post;

class PostPolicy
{
    public function update(User $user, Post $post)
    {
        // 投稿者本人のみ編集可能
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post)
    {
        // 投稿者本人のみ削除可能
        return $user->id === $post->user_id;
    }
}

③AuthServiceProviderで登録する。

// app/Providers/AuthServiceProvider.php

protected $policies = [
    \App\Models\Post::class => \App\Policies\PostPolicy::class,
];

Bladeテンプレートで使用する場合

@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">編集</a>
@endcan

@can('delete', $post)
    <form method="POST" action="{{ route('posts.destroy', $post) }}">
        @csrf
        @method('DELETE')
        <button type="submit">削除</button>
    </form>
@endcan

コントローラーで使用する場合

public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);

    // 認可OKなら更新処理
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?