Readouble

Laravel master 認可

イントロダクションIntroduction

Laravelは組み込み済みの認証サービスに加え、特定のリソースに対するユーザアクションを認可する簡単な手法も提供しています。認証と同様に、Laravelの認可のアプローチはシンプルで、主に2つの認可アクションの方法があります。ゲートとポリシーです。In addition to providing authentication[/docs/{{version}}/authentication] services out of the box, Laravel also provides a simple way to authorize user actions against a given resource. Like authentication, Laravel's approach to authorization is simple, and there are two primary ways of authorizing actions: gates and policies.

ゲートとポリシーは、ルートとコントローラのようなものであると考えてください。ゲートはシンプルな、クロージャベースのアプローチを認可に対してとっています。一方のコントローラに似ているポリシーとは、特定のモデルやリソースに対するロジックをまとめたものです。最初にゲートを説明し、次にポリシーを確認しましょう。Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource. We'll explore gates first and then examine policies.

ゲートとポリシーをアプリケーション上、相互に反する機能と捉えないことは重要です。ほとんどのアプリケーションでゲートとポリシーは混在して使われますが、それで正しいのです。管理者のダッシュボードのように、モデルやリソースとは関連しないアクションに対し、ゲートは主に適用されます。それに対し、ポリシーは特定のモデルやリソースに対するアクションを認可したい場合に、使用する必要があります。It is important to not view gates and policies as mutually exclusive for your application. Most applications will most likely contain a mixture of gates and policies, and that is perfectly fine! Gates are most applicable to actions which are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource.

ゲートGates

ゲートの記述Writing Gates

ゲートは、特定のアクションを実行できる許可が、あるユーザにあるかを決めるクロージャのことです。通常は、App\Providers\AuthServiceProviderの中で、Gateファサードを使用し、定義します。ゲートは常に最初の引数にユーザインスタンスを受け取ります。関連するEloquentモデルのような、追加の引数をオプションとして受け取ることもできます。Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the App\Providers\AuthServiceProvider class using the Gate facade. Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model:

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Gate::define('update-post', function ($user, $post) {
        return $user->id == $post->user_id;
    });
}

アクションの認可Authorizing Actions

ゲートを使用しアクションを認可するには、allowsメソッドを使ってください。allowsメソッドに現在認証中のユーザを渡す必要はないことに注目しましょう。Laravelが自動的にゲートクロージャにユーザを渡します。To authorize an action using gates, you should use the allows method. Note that you are not required to pass the currently authenticated user to the allows method. Laravel will automatically take care of passing the user into the gate Closure:

if (Gate::allows('update-post', $post)) {
    // 現在のユーザはこのポストを更新できる
}

特定のユーザがあるアクションを実行できる認可を持っているかを確認するには、GateファサードのforUserメソッドを使用します。If you would like to determine if a particular user is authorized to perform an action, you may use the forUser method on the Gate facade:

if (Gate::forUser($user)->allows('update-post', $post)) {
    // 渡されたユーザはこのポストを更新できる
}

ポリシー作成Creating Policies

ポリシーの生成Generating Policies

ポリシーは特定のモデルやリソースに関する認可ロジックを系統立てるクラスです。たとえば、ブログアプリケーションの場合、Postモデルとそれに対応する、ポストを作成/更新するなどのユーザアクションを認可するPostPolicyを持つことになるでしょう。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.

make:policy Artisanコマンドを使用し、ポリシーを生成できます。生成したポリシーはapp/Policiesディレクトリに設置されます。このディレクトリがアプリケーションに存在していなくても、Laravelにより作成されます。You may generate a policy using the make:policy artisan command[/docs/{{version}}/artisan]. The generated policy will be placed in the app/Policies directory. If this directory does not exist in your application, Laravel will create it for you:

php artisan make:policy PostPolicy

make:policyコマンドは空のポリシークラスを生成します。基本的な「CRUD」ポリシーメソッドを生成するクラスへ含めたい場合は、make:policyコマンド実行時に--modelを指定してください。The make:policy command will generate an empty policy class. If you would like to generate a class with the basic "CRUD" policy methods already included in the class, you may specify a --model when executing the command:

php artisan make:policy PostPolicy --model=Post

lightbulb">Tip!! 全ポリシーはLaravelの サービスコンテナにより依存解決されるため、ポリシーのコンストラクタに必要な依存をタイプヒントすれば、自動的に注入されます。{tip} All policies are resolved via the Laravel service container[/docs/{{version}}/container], allowing you to type-hint any needed dependencies in the policy's constructor to have them automatically injected.

ポリシーの登録Registering Policies

ポリシーができたら、登録する必要があります。インストールしたLaravelアプリケーションに含まれている、AuthServiceProviderにはEloquentモデルと対応するポリシーをマップするためのpoliciesプロパティを含んでいます。ポリシーの登録とは、指定したモデルに対するアクションの認可時に、どのポリシーを利用するかをLaravelへ指定することです。Once the policy exists, it needs to be registered. The AuthServiceProvider included with fresh Laravel applications contains a policies property which maps your Eloquent models to their corresponding policies. Registering a policy will instruct Laravel which policy to utilize when authorizing actions against a given model:

<?php

namespace App\Providers;

use App\Post;
use App\Policies\PostPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションにマップ付されたポリシー
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

    /**
     * アプリケーションの全認証/認可サービスの登録
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

ポリシーの記述Writing Policies

ポリシーのメソッドPolicy Methods

ポリシーが登録できたら、認可するアクションごとにメソッドを追加します。たとえば、指定したUserが指定Postインスタンスの更新をできるか決める、updataメソッドをPostPolicyに定義してみましょう。Once the policy has been registered, you may add methods for each action it authorizes. For example, let's define an update method on our PostPolicy which determines if a given User can update a given Post instance.

updateメソッドはUserPostインスタンスを引数で受け取り、ユーザが指定Postの更新を行う認可を持っているかを示す、truefalseを返します。ですから、この例の場合、ユーザのidとポストのuser_idが一致するかを確認しましょう。The update method will receive a User and a Post instance as its arguments, and should return true or false indicating whether the user is authorized to update the given Post. So, for this example, let's verify that the user's id matches the user_id on the post:

<?php

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
    /**
     * ユーザにより指定されたポストが更新可能か決める
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

必要に応じ、様々なアクションを認可するために、追加のメソッドをポリシーに定義してください。たとえば、色々なPostアクションを認可するために、viewdeleteメソッドを追加できます。ただし、ポリシーのメソッドには好きな名前を自由につけられることを覚えておいてください。You may continue to define additional methods on the policy as needed for the various actions it authorizes. For example, you might define view or delete methods to authorize various Post actions, but remember you are free to give your policy methods any name you like.

lightbulb">Tip!! ポリシーを--modelオプションを付け、Artisanコマンドにより生成した場合、viewcreateupdatedeleteアクションが含まれています。{tip} If you used the --model option when generating your policy via the Artisan console, it will already contain methods for the view, create, update, and delete actions.

モデルを持たないメソッドMethods Without Models

ポリシーメソッドの中には、現在の認証ユーザのみを受け取り、認可するためのモデルを必要としないものもあります。この状況は、createアクションを認可する場合に、よく現れます。たとえば、ブログを作成する場合、どんなポストかにはかかわらず、そのユーザが作成可能かを認可したいでしょう。Some policy methods only receive the currently authenticated user and not an instance of the model they authorize. This situation is most common when authorizing create actions. For example, if you are creating a blog, you may wish to check if a user is authorized to create any posts at all.

createのように、モデルインスタンスを受け取らないポリシーメソッドを定義する場合は、モデルインスタンスを受け取る必要はありません。代わりに、その認証済みユーザが期待している人物かをメソッドで定義してください。When defining policy methods that will not receive a model instance, such as a create method, it will not receive a model instance. Instead, you should define the method as only expecting the authenticated user:

/**
 * 指定されたユーザがポストを作成できるかを決める
 *
 * @param  \App\User  $user
 * @return bool
 */
public function create(User $user)
{
    //
}

lightbulb">Tip!! ポリシー生成時に--modelオプションを使用している場合、「CRUD」に関連するポリシーメソッドはすでに定義済みです。{tip} If you used the --model option when generating your policy, all of the relevant "CRUD" policy methods will already be defined on the generated policy.

ポリシーフィルダーPolicy Filters

特定のユーザには指定したポリシーの全アクションを許可したい場合があります。そのためには、beforeメソッドをポリシーへ定義してください。beforeメソッドはポリシーの他のメソッドの前に実行されるため、意図するポリシーメソッドが実際に呼び出される前に、アクションを許可する機会を提供します。この機能は主に、アプリケーションの管理者に全てのアクションを実行する権限を与えるために使用されます。For certain users, you may wish to authorize all actions within a given policy. To accomplish this, define a before method on the policy. The before method will be executed before any other methods on the policy, giving you an opportunity to authorize the action before the intended policy method is actually called. This feature is most commonly used for authorizing application administrators to perform any action:

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

ポリシーを使ったアクションの認可Authorizing Actions Using Policies

Userモデルによる確認Via The User Model

Laravelアプリケーションに含まれるUserモデルは、アクションを認可するための便利な2つのメソッドを持っています。cancantです。canメソッドは認可したいアクションと関連するモデルを引数に取ります。例として、ユーザが指定したPostを更新を認可するかを決めてみましょう。The User model that is included with your Laravel application includes two helpful methods for authorizing actions: can and cant. The can method receives the action you wish to authorize and the relevant model. For example, let's determine if a user is authorized to update a given Post model:

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

指定するモデルのポリシーが登録済みであれば適切なポリシーのcanメソッドが自動的に呼びだされ、論理型の結果が返されます。そのモデルに対するポリシーが登録されていない場合、canメソッドは指定したアクション名に合致する、ゲートベースのクロージャーを呼びだそうとします。If a policy is registered[#registering-policies] for the given model, the can method will automatically call the appropriate policy and return the boolean result. If no policy is registered for the model, the can method will attempt to call the Closure based Gate matching the given action name.

モデルを必要としないアクションActions That Don't Require Models

createのようなアクションは、モデルインスタンスを必要としないことを思い出してください。そうした場合は、canメソッドにはクラス名を渡してください。クラス名はアクションを認可するときにどのポリシーを使用すべきかを決めるために使われます。Remember, some actions like create may not require a model instance. In these situations, you may pass a class name to the can method. The class name will be used to determine which policy to use when authorizing the action:

use App\Post;

if ($user->can('create', Post::class)) {
    // 関連するポリシーの"create"メソッドが実行される
}

ミドルウェアによる認可Via Middleware

送信されたリクエストがルートやコントローラへ到達する前に、アクションを認可できるミドルウェアをLaravelは持っています。デフォルトでApp\Http\Kernelクラスの中でcanキーにIlluminate\Auth\Middleware\Authorizeミドルウェアが割り付けられています。あるユーザがブログポストを認可するために、canミドルウェアを使う例をご覧ください。Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers. By default, the Illuminate\Auth\Middleware\Authorize middleware is assigned the can key in your App\Http\Kernel class. Let's explore an example of using the can middleware to authorize that a user can update a blog post:

use App\Post;

Route::put('/post/{post}', function (Post $post) {
    // 現在のユーザはこのポストを更新できる
})->middleware('can:update,post');

この例では、canミドルウェアへ2つの引数を渡しています。最初の引数は認可したいアクションの名前です。2つ目はポリシーメソッドに渡したいルートパラメータです。この場合、暗黙のモデル結合を使用しているため、Postモデルがポリシーメソッドへ渡されます。ユーザに指定したアクションを実行する認可がない場合、ミドルウェアにより403ステータスコードのHTTPレスポンスが生成されます。In this example, we're passing the can middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method. In this case, since we are using implicit model binding[/docs/{{version}}/routing#implicit-binding], a Post model will be passed to the policy method. If the user is not authorized to perform the given action, a HTTP response with a 403 status code will be generated by the middleware.

モデルを必要としないアクションActions That Don't Require Models

この場合も、createのようなアクションではモデルインスタンスを必要としていません。こうした場合、ミドルウェアへクラス名を渡してください。クラス名はアクションを認可するときに、どのポリシーを使用するかに使われます。Again, some actions like create may not require a model instance. In these situations, you may pass a class name to the middleware. The class name will be used to determine which policy to use when authorizing the action:

Route::post('/post', function () {
    // 現在のユーザはポストを更新できる
})->middleware('can:create,App\Post');

コントローラヘルパによる認可Via Controller Helpers

Userモデルが提供している便利なメソッドに付け加え、App\Http\Controllers\Controllerベースクラスを拡張しているコントローラに対し、Laravelはauthorizeメソッドを提供しています。canメソッドと同様に、このメソッドは認可対象のアクション名と関連するモデルを引数に取ります。アクションが認可されない場合、authorizeメソッドはIlluminate\Auth\Access\AuthorizationException例外を投げ、これはデフォルトでLaravelの例外ハンドラにより、403ステータスコードのHTTPレスポンスへ変換されます。In addition to helpful methods provided to the User model, Laravel provides a helpful authorize method to any of your controllers which extend the App\Http\Controllers\Controller base class. Like the can method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the authorize method will throw an Illuminate\Auth\Access\AuthorizationException, which the default Laravel exception handler will convert to an HTTP response with a 403 status code:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * 指定したポストの更新
     *
     * @param  Request  $request
     * @param  Post  $post
     * @return Response
     */
    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);

        // 現在のユーザはブログポストの更新が可能
    }
}

モデルを必要としないアクションActions That Don't Require Models

既に説明してきたように、createのように、モデルインスタンスを必要としないアクションがあります。この場合、クラス名をauthorizeメソッドへ渡してください。クラス名はアクションの認可時に、どのポリシーを使用するのかを決めるために使われます。As previously discussed, some actions like create may not require a model instance. In these situations, you may pass a class name to the authorize method. The class name will be used to determine which policy to use when authorizing the action:

/**
 * 新しいブログポストの生成
 *
 * @param  Request  $request
 * @return Response
 */
public function create(Request $request)
{
    $this->authorize('create', Post::class);

    // 現在のユーザはブログポストを生成できる
}

Bladeテンプレートによる認可Via Blade Templates

Bladeテンプレートを書くとき、指定したアクションを実行できる認可があるユーザの場合のみ、ページの一部分を表示したい場合があります。たとえば、実際にポストを更新できるユーザの場合のみ、ブログポストの更新フォームを表示したい場合です。この場合、@can@cannotディレクティブを使います。When writing Blade templates, you may wish to 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 directives.

@can('update', $post)
    <!-- 現在のユーザはポストを更新できる -->
@endcan

@cannot('update', $post)
    <!-- 現在のユーザはポストを更新できない -->
@endcannot

両ディレクティブは@if@unless文を使う記述の、便利な短縮形です。上記の@can@cannot文に対応するコードは以下のようになります。These directives are convenient short-cuts for writing @if and @unless statements. The @can and @cannot statements above respectively translate to the following statements:

@if (Auth::user()->can('update', $post))
    <!-- 現在のユーザはポストを更新できる -->
@endif

@unless (Auth::user()->can('update', $post))
    <!-- 現在のユーザはポストを更新できない -->
@endunless

モデルを必要としないアクションActions That Don't Require Models

他の認可メソッドと同様に、アクションがモデルインスタンスを必要としない場合、@can@cannotディレクティブへ、クラス名を渡すことができます。Like most of the other authorization methods, you may pass a class name to the @can and @cannot directives if the action does not require a model instance:

@can('create', Post::class)
    <!-- 現在のユーザはポストを更新できる -->
@endcan

@cannot('create', Post::class)
    <!-- 現在のユーザはポストを更新できない -->
@endcannot

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作