Readouble

Laravel 8.x コントローラ

イントロダクションIntroduction

すべてのリクエスト処理ロジックをルートファイルのクロージャとして定義する代わりに、「コントローラ」クラスを使用してこの動作を整理することを推奨します。コントローラにより、関係するリクエスト処理ロジックを単一のクラスにグループ化できます。たとえば、UserControllerクラスは、ユーザーの表示、作成、更新、削除など、ユーザーに関連するすべての受信リクエストを処理するでしょう。コントローラはデフォルトで、app/Http/Controllersディレクトリに保存します。Instead of defining all of your request handling logic as closures in your route files, you may wish to organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a UserController class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the app/Http/Controllers directory.

コントローラを書くWriting Controllers

基本のコントローラBasic Controllers

基本的なコントローラの一例を見てみましょう。コントローラは、Laravelに含まれている基本コントローラクラス、App\Http\Controllers\Controllerを拡張することに注意してください::Let's take a look at an example of a basic controller. Note that the controller extends the base controller class included with Laravel: App\Http\Controllers\Controller:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    /**
     * 指定ユーザーのプロファイルを表示
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        return view('user.profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}

このコントローラメソッドのルートは、次のように定義できます。You can define a route to this controller method like so:

use App\Http\Controllers\UserController;

Route::get('/user/{id}', [UserController::class, 'show']);

受信リクエストが指定したルートURIに一致すると、App\Http\Controllers\UserControllerクラスのshowメソッドが呼び出され、ルートパラメータがメソッドに渡されます。When an incoming request matches the specified route URI, the show method on the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to the method.

lightbulb">Tip!! コントローラは基本クラスを拡張する必要はありません。ただし、middlewareauthorizeメソッドなどの便利な機能にはアクセスできません。{tip} Controllers are not required to extend a base class. However, you will not have access to convenient features such as the middleware and authorize methods.

シングルアクションコントローラSingle Action Controllers

コントローラのアクションがとくに複雑な場合は、コントローラクラス全体をその単一のアクション専用にするのが便利です。これを利用するには、コントローラ内で単一の__invokeメソッドを定義します。If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single __invoke method within the controller:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class ProvisionServer extends Controller
{
    /**
     * 新しいWebサーバをプロビジョニング
     *
     * @return \Illuminate\Http\Response
     */
    public function __invoke()
    {
        // ...
    }
}

シングルアクションコントローラのルートを登録する場合、コントローラ方式を指定する必要はありません。代わりに、コントローラの名前をルーターに渡すだけです。When registering routes for single action controllers, you do not need to specify a controller method. Instead, you may simply pass the name of the controller to the router:

use App\Http\Controllers\ProvisionServer;

Route::post('/server', ProvisionServer::class);

make:controller Artisanコマンドで--invokableオプションを指定すると、__invokeメソッドを含んだコントローラを生成できます。You may generate an invokable controller by using the --invokable option of the make:controller Artisan command:

php artisan make:controller ProvisionServer --invokable

lightbulb">Tip!! stubのリソース公開を使用し、コントローラのスタブをカスタマイズできます。{tip} Controller stubs may be customized using stub publishing[/docs/{{version}}/artisan#stub-customization].

コントローラミドルウェアController Middleware

ミドルウェアはルートファイルの中で、コントローラのルートに対して指定します。Middleware[/docs/{{version}}/middleware] may be assigned to the controller's routes in your route files:

Route::get('profile', [UserController::class, 'show'])->middleware('auth');

または、コントローラのコンストラクター内でミドルウェアを指定できると便利な場合があります。コントローラのコンストラクタ内でmiddlewareメソッドを使用して、コントローラのアクションにミドルウェアを割り当てられます。Or, you may find it convenient to specify middleware within your controller's constructor. Using the middleware method within your controller's constructor, you can assign middleware to the controller's actions:

class UserController extends Controller
{
    /**
     * 新しいUserControllerインスタンスの生成
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('log')->only('index');
        $this->middleware('subscribed')->except('store');
    }
}

コントローラでは、クロージャを使用したミドルウェアの登録もできます。これにより、ミドルウェアクラス全体を定義せずに、単一のコントローラ用のインラインミドルウェアを便利に定義できます。Controllers also allow you to register middleware using a closure. This provides a convenient way to define an inline middleware for a single controller without defining an entire middleware class:

$this->middleware(function ($request, $next) {
    return $next($request);
});

リソースコントローラResource Controllers

アプリケーション内の各Eloquentモデルを「リソース」と考える場合、通常、アプリケーション内の各リソースに対して同じ一連のアクションを実行します。たとえば、アプリケーションにPhotoモデルとMovieモデルが含まれているとします。ユーザーはこれらのリソースを作成、読み取り、更新、または削除できるでしょう。If you think of each Eloquent model in your application as a "resource", it is typical to perform the same sets of actions against each resource in your application. For example, imagine your application contains a Photo model and a Movie model. It is likely that users can create, read, update, or delete these resources.

このようなコモン・ケースのため、Laravelリソースルーティングは、通常の作成、読み取り、更新、および削除("CRUD")ルートを1行のコードでコントローラに割り当てます。使用するには、make:controller Artisanコマンドへ--resourceオプションを指定すると、こうしたアクションを処理するコントローラをすばやく作成できます。Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the make:controller Artisan command's --resource option to quickly create a controller to handle these actions:

php artisan make:controller PhotoController --resource

このコマンドは、app/Http/Controllers/PhotoController.phpにコントローラを生成します。コントローラには、そのまま使用可能な各リソース操作のメソッドを用意してあります。次に、コントローラを指すリソースルートを登録しましょう。This command will generate a controller at app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations. Next, you may register a resource route that points to the controller:

use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class);

この一つのルート宣言で、リソースに対するさまざまなアクションを処理するための複数のルートを定義しています。生成したコントローラには、これらのアクションごとにスタブしたメソッドがすでに含まれています。route:list Artisanコマンドを実行すると、いつでもアプリケーションのルートの概要をすばやく確認できます。This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions. Remember, you can always get a quick overview of your application's routes by running the route:list Artisan command.

配列をresourcesメソッドに渡すことで、一度に多くのリソースコントローラを登録することもできます。You may even register many resource controllers at once by passing an array to the resources method:

Route::resources([
    'photos' => PhotoController::class,
    'posts' => PostController::class,
]);

リソースコントローラにより処理されるアクションActions Handled By Resource Controller

動詞Verb URIURI アクションAction ルート名Route Name
GETGET /photos/photos indexindex photos.indexphotos.index
GETGET /photos/create/photos/create createcreate photos.createphotos.create
POSTPOST /photos/photos storestore photos.storephotos.store
GETGET /photos/{photo}/photos/{photo} showshow photos.showphotos.show
GETGET /photos/{photo}/edit/photos/{photo}/edit editedit photos.editphotos.edit
PUT/PATCHPUT/PATCH /photos/{photo}/photos/{photo} updateupdate photos.updatephotos.update
DELETEDELETE /photos/{photo}/photos/{photo} destroydestroy photos.destroyphotos.destroy

見つからないモデルの動作のカスタマイズCustomizing Missing Model Behavior

暗黙的にバインドしたリソースモデルが見つからない場合、通常404のHTTPレスポンスが生成されます。ただし、リソースルートを定義するときにmissingメソッドを呼び出すことでこの動作をカスタマイズすることができます。missingメソッドは、暗黙的にバインドされたモデルがリソースのルートに対して見つからない場合に呼び出すクロージャを引数に取ります。Typically, a 404 HTTP response will be generated if an implicitly bound resource model is not found. However, you may customize this behavior by calling the missing method when defining your resource route. The missing method accepts a closure that will be invoked if an implicitly bound model can not be found for any of the resource's routes:

use App\Http\Controllers\PhotoController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

Route::resource('photos', PhotoController::class)
        ->missing(function (Request $request) {
            return Redirect::route('photos.index');
        });

リソースモデルの指定Specifying The Resource Model

ルートモデル結合を使用していて、リソースコントローラのメソッドでモデルインスタンスをタイプヒントしたい場合は、コントローラを生成するときのオプションに--modelを使用します。If you are using route model binding[/docs/{{version}}/routing#route-model-binding] and would like the resource controller's methods to type-hint a model instance, you may use the --model option when generating the controller:

php artisan make:controller PhotoController --model=Photo --resource

フォームリクエストの生成Generating Form Requests

リソースコントローラの生成時に、--requestsオプションを指定すると、コントローラの保存と更新メソッド用にフォームリクエストクラスを生成するようにArtisanへ指定できます。You may provide the --requests option when generating a resource controller to instruct Artisan to generate form request classes[/docs/{{version}}/validation#form-request-validation] for the controller's storage and update methods:

php artisan make:controller PhotoController --model=Photo --resource --requests

部分的なリソースルートPartial Resource Routes

リソースルートの宣言時に、デフォルトアクション全部を指定する代わりに、ルートで処理するアクションの一部を指定可能です。When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions:

use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class)->only([
    'index', 'show'
]);

Route::resource('photos', PhotoController::class)->except([
    'create', 'store', 'update', 'destroy'
]);

APIリソースルートAPI Resource Routes

APIに使用するリソースルートを宣言する場合、createeditのようなHTMLテンプレートを提供するルートを除外したいことがよく起こります。そのため、これらの2ルートを自動的に除外する、apiResourceメソッドが使用できます。When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as create and edit. For convenience, you may use the apiResource method to automatically exclude these two routes:

use App\Http\Controllers\PhotoController;

Route::apiResource('photos', PhotoController::class);

apiResourcesメソッドに配列として渡すことで、一度に複数のAPIリソースコントローラを登録できます。You may register many API resource controllers at once by passing an array to the apiResources method:

use App\Http\Controllers\PhotoController;
use App\Http\Controllers\PostController;

Route::apiResources([
    'photos' => PhotoController::class,
    'posts' => PostController::class,
]);

createeditメソッドを含まないAPIリソースコントローラを素早く生成するには、make:controllerコマンドを実行する際、--apiスイッチを使用してください。To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller PhotoController --api

ネストしたリソースNested Resources

ネストしたリソースへのルートを定義したい場合もあるでしょう。たとえば、写真リソースは、写真へ投稿された複数のコメントを持っているかもしれません。リソースコントローラをネストするには、ルート宣言で「ドット」表記を使用します。Sometimes you may need to define routes to a nested resource. For example, a photo resource may have multiple comments that may be attached to the photo. To nest the resource controllers, you may use "dot" notation in your route declaration:

use App\Http\Controllers\PhotoCommentController;

Route::resource('photos.comments', PhotoCommentController::class);

このルートにより次のようなURLでアクセスする、ネストしたリソースが定義できます。This route will register a nested resource that may be accessed with URIs like the following:

/photos/{photo}/comments/{comment}

ネストしたリソースのスコープScoping Nested Resources

Laravelの暗黙的なモデル結合機能は、リソース解決する子モデルが親モデルに属することを確認するように、ネストした結合を自動的にスコープできます。ネストしたリソースを定義するときにscopedメソッドを使用することにより、自動スコープを有効にしたり、子リソースを取得するフィールドをLaravelに指示したりできます。この実現方法の詳細は、リソースルートのスコープに関するドキュメントを参照してください。Laravel's implicit model binding[/docs/{{version}}/routing#implicit-model-binding-scoping] feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the scoped method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by. For more information on how to accomplish this, please see the documentation on scoping resource routes[#restful-scoping-resource-routes].

ShallowネストShallow Nesting

子のIDがすでに一意な識別子になってる場合、親子両方のIDをURIに含める必要はまったくありません。主キーの自動増分のように、一意の識別子をURIセグメント中でモデルを識別するために使用しているのなら、「shallow(浅い)ネスト」を使用できます。Often, it is not entirely necessary to have both the parent and the child IDs within a URI since the child ID is already a unique identifier. When using unique identifiers such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use "shallow nesting":

use App\Http\Controllers\CommentController;

Route::resource('photos.comments', CommentController::class)->shallow();

このルート定義は、以下のルートを定義します。This route definition will define the following routes:

動詞Verb URIURI アクションAction ルート名Route Name
GETGET /photos/{photo}/comments/photos/{photo}/comments indexindex photos.comments.indexphotos.comments.index
GETGET /photos/{photo}/comments/create/photos/{photo}/comments/create createcreate photos.comments.createphotos.comments.create
POSTPOST /photos/{photo}/comments/photos/{photo}/comments storestore photos.comments.storephotos.comments.store
GETGET /comments/{comment}/comments/{comment} showshow comments.showcomments.show
GETGET /comments/{comment}/edit/comments/{comment}/edit editedit comments.editcomments.edit
PUT/PATCHPUT/PATCH /comments/{comment}/comments/{comment} updateupdate comments.updatecomments.update
DELETEDELETE /comments/{comment}/comments/{comment} destroydestroy comments.destroycomments.destroy

リソースルートの命名Naming Resource Routes

すべてのリソースコントローラアクションにはデフォルトのルート名があります。ただし、names配列に指定したいルート名を渡すことで、この名前を上書きできます。By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your desired route names:

use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class)->names([
    'create' => 'photos.build'
]);

リソースルートパラメータの命名Naming Resource Route Parameters

Route::resourceはデフォルトで、リソース名の「単数形」バージョンに基づいて、リソースルートのルートパラメータを作成します。parametersメソッドを使用して、リソースごとにこれを簡単にオーバーライドできます。parametersメソッドに渡す配列は、リソース名とパラメーター名の連想配列である必要があります。By default, Route::resource will create the route parameters for your resource routes based on the "singularized" version of the resource name. You can easily override this on a per resource basis using the parameters method. The array passed into the parameters method should be an associative array of resource names and parameter names:

use App\Http\Controllers\AdminUserController;

Route::resource('users', AdminUserController::class)->parameters([
    'users' => 'admin_user'
]);

上記の例では、リソースのshowルートに対して以下のURIが生成されます。The example above generates the following URI for the resource's show route:

/users/{admin_user}

リソースルートのスコープScoping Resource Routes

Laravelのスコープ付き暗黙モデル結合機能は、解決する子モデルが親モデルに属することを確認するように、ネストした結合を自動的にスコープできます。ネストしたリソースを定義するときにscopedメソッドを使用することで、自動スコープを有効にし、以下のように子リソースを取得するフィールドをLaravelに指示できます。Laravel's scoped implicit model binding[/docs/{{version}}/routing#implicit-model-binding-scoping] feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the scoped method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by:

use App\Http\Controllers\PhotoCommentController;

Route::resource('photos.comments', PhotoCommentController::class)->scoped([
    'comment' => 'slug',
]);

このルートは、以下のようなURIでアクセスする、スコープ付きのネストしたリソースを登録します。This route will register a scoped nested resource that may be accessed with URIs like the following:

/photos/{photo}/comments/{comment:slug}

ネストしたルートパラメーターとしてカスタムキー付き暗黙的結合を使用する場合、親からネストしているモデルを取得するために、Laravelはクエリのスコープを自動的に設定し、親のリレーション名を推測する規則を使用します。この場合、Photoモデルには、Commentモデルを取得するために使用できるcomments(ルートパラメータ名の複数形)という名前のリレーションがあると想定します。When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the Photo model has a relationship named comments (the plural of the route parameter name) which can be used to retrieve the Comment model.

リソースURIのローカライズLocalizing Resource URIs

Route::resourceはデフォルトで、英語の動詞を使用してリソースURIを作成します。createおよびeditアクション動詞をローカライズする必要がある場合は、Route::resourceVerbsメソッドを使用します。これは、アプリケーションのApp\Providers\RouteServiceProvider内のbootメソッドの先頭で実行します。By default, Route::resource will create resource URIs using English verbs. If you need to localize the create and edit action verbs, you may use the Route::resourceVerbs method. This may be done at the beginning of the boot method within your application's App\Providers\RouteServiceProvider:

/**
 * ルートモデルの結合、パターンフィルターなどを定義
 *
 * @return void
 */
public function boot()
{
    Route::resourceVerbs([
        'create' => 'crear',
        'edit' => 'editar',
    ]);

    // ...
}

動詞をカスタマイズすると、Route::resource('fotos'、PhotoController::class)などのリソースルート登録により、次のURIが生成されます。Once the verbs have been customized, a resource route registration such as Route::resource('fotos', PhotoController::class) will produce the following URIs:

/fotos/crear

/fotos/{foto}/editar

リソースコントローラへのルート追加Supplementing Resource Controllers

リソースルートのデフォルトセットを超えてリソースコントローラにルートを追加する必要がある場合は、Route::resourceメソッドを呼び出す前にそれらのルートを定義する必要があります。そうしないと、resourceメソッドで定義されたルートが、意図せずに補足ルートよりも優先される可能性があります。If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to the Route::resource method; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

use App\Http\Controller\PhotoController;

Route::get('/photos/popular', [PhotoController::class, 'popular']);
Route::resource('photos', PhotoController::class);

lightbulb">Tip!! コントローラの責務を限定することを思い出してください。典型的なリソースアクションから外れたメソッドが繰り返して必要になっているようであれば、コントローラを2つに分け、小さなコントローラにすることを考えましょう。{tip} Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers.

依存注入とコントローラDependency Injection & Controllers

コンストラクターインジェクションConstructor Injection

全コントローラの依存を解決するために、Laravelのサービスコンテナが使用されます。これにより、コントローラが必要な依存をコンストラクターにタイプヒントで指定できるのです。依存クラスは自動的に解決され、コントローラへインスタンスが注入されます。The Laravel service container[/docs/{{version}}/container] is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The declared dependencies will automatically be resolved and injected into the controller instance:

<?php

namespace App\Http\Controllers;

use App\Repositories\UserRepository;

class UserController extends Controller
{
    /**
     * ユーザーリポジトリインスタンス
     */
    protected $users;

    /**
     * 新しいコントローラインスタンスの生成
     *
     * @param  \App\Repositories\UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
}

メソッドインジェクションMethod Injection

コンストラクターによる注入に加え、コントローラのメソッドでもタイプヒントにより依存を指定することもできます。メソッドインジェクションの典型的なユースケースは、コントローラメソッドへIlluminate\Http\Requestインスタンスを注入する場合です。In addition to constructor injection, you may also type-hint dependencies on your controller's methods. A common use-case for method injection is injecting the Illuminate\Http\Request instance into your controller methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 新ユーザーの保存
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $name = $request->name;

        //
    }
}

コントローラメソッドへルートパラメーターによる入力値が渡される場合も、依存定義の後に続けてルート引数を指定します。たとえば以下のようにルートが定義されていれば:If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. For example, if your route is defined like so:

use App\Http\Controllers\UserController;

Route::put('/user/{id}', [UserController::class, 'update']);

下記のようにIlluminate\Http\Requestをタイプヒントで指定しつつ、コントローラメソッドで定義しているidパラメータにアクセスできます。You may still type-hint the Illuminate\Http\Request and access your id parameter by defining your controller method as follows:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 指定ユーザーの更新
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }
}

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作