Readouble

Laravel 5.5 コントローラ

イントロダクションIntroduction

全リクエストの処理をルートファイルのクロージャで定義するよりも、コントローラクラスにより組織立てたいと、皆さんも考えるでしょう。関連のあるHTTPリクエストの処理ロジックを一つのクラスへまとめ、グループ分けができます。コントローラはapp/Http/Controllersディレクトリ下に設置します。Instead of defining all of your request handling logic as Closures in route files, you may wish to organize this behavior using Controller classes. Controllers can group related request handling logic into a single class. Controllers are stored in the app/Http/Controllers directory.

基本のコントローラBasic Controllers

コントローラの定義Defining Controllers

これは基本的なコントローラの一例です。全てのLaravelコントローラはLaravelに含まれている基本コントローラクラスを拡張します。コントローラアクションにミドルウェアを追加するために使うmiddlewareメソッドのように、便利なメソッドをベースクラスは提供しています。Below is an example of a basic controller class. Note that the controller extends the base controller class included with Laravel. The base class provides a few convenience methods such as the middleware method, which may be used to attach middleware to controller actions:

<?php

namespace App\Http\Controllers;

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

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

コントローラアクションへルート付けるには、次のようにします。You can define a route to this controller action like so:

Route::get('user/{id}', 'UserController@show');

これで指定したルートのURIにリクエストが一致すれば、UserControllershowメソッドが実行されます。もちろん、ルートパラメーターはメソッドに渡されます。Now, when a request matches the specified route URI, the show method on the UserController class will be executed. Of course, the route parameters will also be passed to the method.

lightbulb">Tip!! コントローラはベースクラスの拡張を要求してはいません。しかし、middlewarevalidatedispatchのような便利な機能へアクセスできなくなります。{tip} Controllers are not required to extend a base class. However, you will not have access to convenience features such as the middleware, validate, and dispatch methods.

コントローラと名前空間Controllers & Namespaces

とても重要な注目ポイントはコントローラルートの定義時に、コントローラの完全な名前空間を指定する必要がないことです。RouteServiceProviderが、コントローラの名前空間を指定したルートグループの中で、ルートファイルをロードしていますので、「先頭」のApp\Http\Controllers名前空間に続くクラス名の部分だけを指定するだけで済みます。It is very important to note that we did not need to specify the full controller namespace when defining the controller route. Since the RouteServiceProvider loads your route files within a route group that contains the namespace, we only specified the portion of the class name that comes after the App\Http\Controllers portion of the namespace.

App\Http\Controllersディレクトリより深く、コントローラのPHP名前空間をネストしたり、組織立てたりする場合でも、先頭のApp\Http\Controllers名前空間からの相対クラス名を指定します。ですから、コントローラの完全なクラス名がApp\Http\Controllers\Photos\AdminControllerならば、次のようにルートを登録します。If you choose to nest your controllers deeper into the App\Http\Controllers directory, use the specific class name relative to the App\Http\Controllers root namespace. So, if your full controller class is App\Http\Controllers\Photos\AdminController, you should register routes to the controller like so:

Route::get('foo', 'Photos\AdminController@method');

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

アクションを一つだけ含むコントローラを定義したい場合は、そのコントローラに__invokeメソッドを設置してください。If you would like to define a controller that only handles a single action, you may place a single __invoke method on the controller:

<?php

namespace App\Http\Controllers;

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

class ShowProfile extends Controller
{
    /**
     * 指定ユーザーのプロフィール表示
     *
     * @param  int  $id
     * @return Response
     */
    public function __invoke($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

シングルアクションコントローラへのルートを定義するとき、メソッドを指定する必要はありません。When registering routes for single action controllers, you do not need to specify a method:

Route::get('user/{id}', 'ShowProfile');

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

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

Route::get('profile', 'UserController@show')->middleware('auth');

もしくは、コントローラのコンストラクタの中でミドルウェアを指定するほうが、より便利でしょう。コントローラのコンストラクタで、middlewareメソッドを使い、コントローラのアクションに対するミドルウェアを簡単に指定できます。コントローラクラスの特定のメソッドに対してのみ、ミドルウェアの適用を制限することもできます。However, it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action. You may even restrict the middleware to only certain methods on the controller class:

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 a middleware for a single controller without defining an entire middleware class:

$this->middleware(function ($request, $next) {
    // ...

    return $next($request);
});

lightbulb">Tip!! コントローラアクションの一部へミドルウェアを適用することはできますが、しかしながら、これはコントローラが大きくなりすぎたことを示しています。代わりに、コントローラを複数の小さなコントローラへ分割することを考えてください。{tip} You may assign middleware to a subset of controller actions; however, it may indicate your controller is growing too large. Instead, consider breaking your controller into multiple, smaller controllers.

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

Laravelリソースルートは一行のコードで、典型的な「CRUD」ルートをコントローラへ割り付けます。たとえば、アプリケーションへ保存されている「写真(photo)」に対する全HTTPリクエストを処理するコントローラを作成したいとしましょう。make:controller Artisanコマンドを使えば、このようなコントローラは素早く生成できます。Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for "photos" stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:

php artisan make:controller PhotoController --resource

このArtisanコマンドは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 resourceful route to the controller:

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

リソースに対する様々なアクションを処理する、複数のルートがこの1定義により生成されます。これらのアクションをHTTP動詞と処理するURIの情報を注記と一緒に含むスタブメソッドとして、生成されたコントローラはすでに含んでいます。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, including notes informing you of the HTTP verbs and URIs they handle.

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

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

リソースコントローラにより処理されるアクション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

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

ルートモデル結合を使用しているが、リソースコントローラのメソッドでタイプヒントされるモデルインスタンスを指定したい場合は、コントローラの生成時に--modelオプションを使用します。If you are using 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 --resource --model=Photo

擬似フォームメソッドSpoofing Form Methods

HTMLフォームはPUTPATCHDELETEリクエストを作成できませんので、HTTP動詞を偽装するために、_method隠しフィールドを追加する必要が起きるでしょう。method_fieldヘルパで、このフィールドを生成できます。Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The method_field helper can create this field for you:

{{ method_field('PUT') }}

部分的なリソースルート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:

Route::resource('photo', 'PhotoController', ['only' => [
    'index', 'show'
]]);

Route::resource('photo', 'PhotoController', ['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:

Route::apiResource('photo', 'PhotoController');

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

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

リソースルートの命名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 options:

Route::resource('photo', 'PhotoController', ['names' => [
    'create' => 'photo.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 by passing parameters in the options array. The parameters array should be an associative array of resource names and parameter names:

Route::resource('user', 'AdminUserController', ['parameters' => [
    'user' => 'admin_user'
]]);

上記のサンプルコードは、リソースのshowルートで次のURIを生成します。The example above generates the following URIs for the resource's show route:

/user/{admin_user}

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

Route::resourceはデフォルトで、リソースURIに英語の動詞を使います。createeditアクションの動詞をローカライズする場合は、Route::resourceVerbsメソッドを使います。このメソッドは、AppServiceProviderbootメソッド中で呼び出します。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 in the boot method of your AppServiceProvider:

use Illuminate\Support\Facades\Route;

/**
 * 全アプリケーションサービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Route::resourceVerbs([
        'create' => 'crear',
        'edit' => 'editar',
    ]);
}

動詞をカスタマイズすると、Route::resource('fotos', 'PhotoController')のようなリソースルートの登録により、以下のようなURIが生成されるようになります。Once the verbs have been customized, a resource route registration such as Route::resource('fotos', 'PhotoController') 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 Route::resource; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

Route::get('photos/popular', 'PhotoController@method');

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

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  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
}

もちろん、Laravelの契約もタイプヒントに指定できます。コンテナが解決できるのであれば、タイプヒントで指定できます。 アプリケーションによっては、依存をコントローラへ注入すれば、より良いテスタビリティが得られるでしょう。Of course, you may also type-hint any Laravel contract[/docs/{{version}}/contracts]. If the container can resolve it, you can type-hint it. Depending on your application, injecting your dependencies into your controller may provide better testability.

メソッドインジェクション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  Request  $request
     * @return 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:

Route::put('user/{id}', 'UserController@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  Request  $request
     * @param  string  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }
}

ルートキャッシュRoute Caching

Note: note ルートキャッシュはクロージャベースのルートには動作しません。ルートキャッシュを使用するには、全クロージャルートをコントローラクラスを使用するように変更する必要があります。{note} Closure based routes cannot be cached. To use route caching, you must convert any Closure routes to controller classes.

アプリケーションがコントローラベースのルート定義だけを使用しているなら、Laravelのルートキャッシュを利用できる利点があります。ルートキャッシュを使用すれば、アプリケーションの全ルートを登録するのに必要な時間を劇的に減らすことができます。ある場合には、ルート登録が100倍も早くなります。ルートキャッシュを登録するには、route:cache Arisanコマンドを実行するだけです。If your application is exclusively using controller based routes, you should take advantage of Laravel's route cache. Using the route cache will drastically decrease the amount of time it takes to register all of your application's routes. In some cases, your route registration may even be up to 100x faster. To generate a route cache, just execute the route:cache Artisan command:

php artisan route:cache

このコマンドを実行後、キャッシュ済みルートファイルが、リクエストのたびに読み込まれます。新しいルートを追加する場合は、新しいルートキャッシュを生成する必要があることを覚えておきましょう。ですからプロジェクトの開発期間の最後に、一度だけroute:cacheを実行するほうが良いでしょう。After running this command, your cached routes file will be loaded on every request. Remember, if you add any new routes you will need to generate a fresh route cache. Because of this, you should only run the route:cache command during your project's deployment.

キャッシュルートのファイルを削除するには、route:clearコマンドを使います。You may use the route:clear command to clear the route cache:

php artisan route:clear

章選択

公式パッケージ

設定

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

ヘッダー項目移動

キーボード操作