イントロダクションIntroduction
全リクエストの処理をたった一つのroutes.phpファイルで定義するよりも、コントローラークラスにより組織立てたいと、皆さんも考えるでしょう。関連のあるHTTPリクエストの処理ロジックを一つのクラスへまとめ、グループ分けができます。コントローラーはapp/Http/Controllersディレクトリ下に設置します。Instead of defining all of your request handling logic in a single routes.php file, you may wish to organize this behavior using Controller classes. Controllers can group related HTTP request handling logic into a class. Controllers are stored in the app/Http/Controllers directory.
基本のコントローラーBasic Controllers
これは基本的なコントローラーの一例です。全てのLaravelコントローラーはLaravelにデフォルトで含まれている基本コントローラークラスを拡張します。Here is an example of a basic controller class. All Laravel controllers should extend the base controller class included with the default Laravel installation:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* 指定ユーザのプロフィール表示
*
* @param int $id
* @return Response
*/
public function showProfile($id)
{
return view('user.profile', ['user' => User::findOrFail($id)]);
}
}
コントローラーアクションへルート付けるには、次のようにします。We can route to the controller action like so:
Route::get('user/{id}', 'UserController@showProfile');
これで指定したルートのURIにリクエストが一致すれば、UserControllerのshowProfileメソッドが実行されます。もちろん、ルートパラメーターはメソッドに渡されます。Now, when a request matches the specified route URI, the showProfile method on the UserController class will be executed. Of course, the route parameters will also be passed to the method.
コントローラーと名前空間Controllers & Namespaces
とても重要な注目ポイントは、コントローラーの完全な名前空間を指定する必要がないことです。「先頭」のApp\Http\Controllers名前空間に続くクラス名の部分だけを指定しています。RouteServiceProviderがコントローラーの名前空間を指定したルートグループの中で、routes.phpファイルをロードします。It is very important to note that we did not need to specify the full controller namespace when defining the controller route. We only defined the portion of the class name that comes after the App\Http\Controllers namespace "root". By default, the RouteServiceProvider will load the routes.php file within a route group containing the root controller namespace.
App\Http\Controllersディレクトリより深く、コントローラのPHP名前空間をネストしたり、組織立てたりする場合でも、単に先頭のApp\Http\Controllers名前空間からの相対クラス名を指定するだけです。ですから、コントローラーの完全なクラス名がApp\Http\Controllers\Photos\AdminControllerならば、次のようにルートを登録します。If you choose to nest or organize your controllers using PHP namespaces deeper into the App\Http\Controllers directory, simply 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 would register a route like so:
Route::get('foo', 'Photos\AdminController@method');
コントローラールートの命名Naming Controller Routes
クロージャルートと同様に、コントローラールートにも名前が指定できます。Like Closure routes, you may specify names on controller routes:
Route::get('foo', ['uses' => 'FooController@method', 'as' => 'name']);
名前付きルートに対するURLを生成するにはrouteヘルパが使用できます。You may also use the route helper to generate a URL to a named controller route:
$url = route('name');
コントローラーミドルウェアController Middleware
ミドルウェアは、コントローラーアクションに対して、次のように指定します。Middleware[/docs/{{version}}/middleware] may be assigned to the controller's routes like so:
Route::get('profile', [
'middleware' => 'auth',
'uses' => 'UserController@showProfile'
]);
またはコントローラーのコンストラクターでも、ミドルウェアを指定できます。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. 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' => [
'fooAction',
'barAction',
]]);
$this->middleware('subscribed', ['except' => [
'fooAction',
'barAction',
]]);
}
}
RESTフルリソースコントローラーRESTful Resource Controllers
リソースフルコントローラーにより、リソースに関するRESTフルコントローラーを苦労せずに構築できます。例えば、アプリケーションで保存されている「写真(phots)」関係のHTTPリクエストを処理するコントローラーを作成するとしましょう。Artisanコマンドラインでmake:controller Artisanコマンドを使えば、対応するコントローラをあっという間に生成できます。Resource controllers make it painless to build RESTful controllers around resources. For example, you may wish to create a controller that handles HTTP requests regarding "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としてコントローラーファイルを生成します。コントローラーは使用可能な各リソース操作に対するメソッドを含んでいます。The Artisan command will generate a controller file 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('photo', 'PhotoController');
写真リソースの様々なRESTフルアクションを処理する多くのルートが、この1行のルート定義で作り出されます。同時に、生成されたコントローラーには、どのURI/動詞を処理するのかという情報を含んだスタブメソッドが、それぞれのアクションに対して用意されています。This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have methods stubbed for each of these actions, including notes informing you which URIs and verbs they handle.
リソースコントローラーにより処理されるアクションActions Handled By Resource Controller
| 動詞Verb | パスPath | アクションAction | ルート名Route Name |
|---|---|---|---|
| GETGET | /photo/photo |
indexindex | photo.indexphoto.index |
| GETGET | /photo/create/photo/create |
createcreate | photo.createphoto.create |
| POSTPOST | /photo/photo |
storestore | photo.storephoto.store |
| GETGET | /photo/{photo}/photo/{photo} |
showshow | photo.showphoto.show |
| GETGET | /photo/{photo}/edit/photo/{photo}/edit |
editedit | photo.editphoto.edit |
| PUT/PATCHPUT/PATCH | /photo/{photo}/photo/{photo} |
updateupdate | photo.updatephoto.update |
| DELETEDELETE | /photo/{photo}/photo/{photo} |
destroydestroy | photo.destroyphoto.destroy |
HTTPフォームはPUT、PATCH、DELETEリクエストを送れないため、HTTP動詞を指定する_method隠しフィールドを付ける必要があります。Remember, 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:
<input type="hidden" name="_method" value="PUT">
部分的なリソースルートPartial Resource Routes
リソースルートの宣言時に、ルートで処理するアクションの一部を指定可能です。When declaring a resource route, you may specify a subset of actions to handle on the route:
Route::resource('photo', 'PhotoController', ['only' => [
'index', 'show'
]]);
Route::resource('photo', 'PhotoController', ['except' => [
'create', 'store', 'update', '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 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 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}
パラメータ名の配列を渡す代わりに、singularを指定すると、Laravelはデフォルトのパラメータ名の「単数形」を使用します。Instead of passing an array of parameter names, you may also simply pass the word singular to instruct Laravel to use the default parameter names, but "singularize" them:
Route::resource('users.photos', 'PhotoController', [
'parameters' => 'singular'
]);
// /users/{user}/photos/{photo}
もしくは、リソースルートパラメータをグローバルに単数形にする、もしくは名前をグローバルにマッピングもできます。Alternatively, you may set your resource route parameters to be globally singular or set a global mapping for your resource parameter names:
Route::singularResourceParameters();
Route::resourceParameters([
'user' => 'person', 'photo' => 'image'
]);
リソースパラメータをカスタマイズする場合、命名のプライオリティを認識しておくことが重要です。When customizing resource parameters, it's important to keep the naming priority in mind:
Route::resourceへ明示的に渡されたパラメータThe parameters explicitly passed toRoute::resource.Route::resourceParametersでグローバルに設定The global parameter mappings set viaRoute::resourceParameters.Route::resourceのparameters配列にsingularを設定するか、Route::singularResourceParametersにより設定Thesingularsetting passed via theparametersarray toRoute::resourceor set viaRoute::singularResourceParameters.- デフォルトの命名規則The default behavior.
リソースコントローラーへのルート追加Supplementing Resource Controllers
デフォルトのリソースルート以外のルートをリソースコントローラーへ追加する場合は、Route::resourceの呼び出しより前に定義する必要があります。そうしないと、resourceメソッドにより定義されるルートが、追加のルートより意図に反して優先されます。If it becomes necessary to add additional routes to a resource controller beyond the default 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');
依存注入とコントローラー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 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.
メソッドインジェクションMethod Injection
コンストラクターによる注入に加え、コントローラーのメソッドでもタイプヒントにより依存を指定することもできます。たとえば、あるメソッドでIlluminate\Http\Requestインスタンスをタイプヒントにより指定してみましょう。In addition to constructor injection, you may also type-hint dependencies on your controller's action methods. For example, let's type-hint the Illuminate\Http\Request instance on one of our 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->input('name');
//
}
}
コントローラーメソッドへルートパラメーターによる入力値が渡される場合でも、依存定義の後に続けてルート引数を指定するだけです。たとえば以下のようにルートが定義されていれば:If your controller method is also expecting input from a route parameter, simply 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 route parameter id by defining your controller method like the following:
<?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: Route caching does not work with Closure based routes. To use route caching, you must convert any Closure routes to use 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
これだけです。キャッシュされたルートファイルは、app/Http/routes.phpファイルの代わりに使用されるようになります。その代わりに、新しいルートの追加を反映するには、キャッシュしたルートを再構築する必要があります。ですからプロジェクトの開発期間の最後に、一度だけroute:cacheを実行するほうが良いでしょう。That's all there is to it! Your cached routes file will now be used instead of your app/Http/routes.php file. 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コマンドを使います。To remove the cached routes file without generating a new cache, use the route:clear command:
php artisan route:clear