基本的なルーティングBasic Routing
アプリケーションのほとんどのルートは、app/Http/routes.phpファイルの中で定義されるでしょう。このファイルは、App\Providers\RouteServiceProviderクラスによりロードされています。一番基本的な、LaravelのルートはURIと「クロージャー」を指定します。You will define most of the routes for your application in the app/Http/routes.php file, which is loaded by the App\Providers\RouteServiceProvider class. The most basic Laravel routes simply accept a URI and a Closure:
基本のGETルートBasic GET Route
Route::get('/', function()
{
return 'Hello World';
});
他の基本ルートOther Basic Routes
Route::post('foo/bar', function()
{
return 'Hello World';
});
Route::put('foo/bar', function()
{
//
});
Route::delete('foo/bar', function()
{
//
});
複数のHTTP動詞に対応するルートの登録Registering A Route For Multiple Verbs
Route::match(['get', 'post'], '/', function()
{
return 'Hello World';
});
全てのHTTP動詞に対応するルートの登録Registering A Route That Responds To Any HTTP Verb
Route::any('foo', function()
{
return 'Hello World';
});
ルートに対するURLを生成する必要が時々起こると思います。urlヘルパを使用できます。Often, you will need to generate URLs to your routes, you may do so using the url helper:
$url = url('foo');
CSRFからの保護CSRF Protection
Laravelでは、クロス・サイト・リクエスト・フォージェリからアプリケーションを簡単に守れます。クロス・サイト・リクエスト・フォージェリは悪意のあるエクスプロイトの一種であり、信頼するユーザーの代わりに、認められていないコマンドを実行します。Laravel makes it easy to protect your application from cross-site request forgeries[http://en.wikipedia.org/wiki/Cross-site_request_forgery]. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of the authenticated user.
Laravelは、アプリケーションにより管理されているアクティブなユーザーの各セッションごとに、CSRF「トークン」を自動的に生成しています。このトークンは認証済みのユーザーが、実装にアプリケーションに対してリクエストを送信しているのかを確認するために役立ちます。Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
CSRFトークンのフォームへの挿入Insert The CSRF Token Into A Form
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
もちろん、Bladeテンプレートエンジンを使用できます。Of course, using the Blade templating engine[/docs/{{version}}/templates]:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
POST、PUT、DELETEリクエストのCSRFトークンを自分で確認する必要はありません。VerifyCsrfToken HTTPミドルウェアが、リクエスト中のトークンとセッションに保存されているトークンが一致するか、確認しています。You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken HTTP middleware[/docs/{{version}}/middleware] will verify token in the request input matches the token stored in the session.
X-CSRF-TOKENX-CSRF-TOKEN
さらに、"POST"パラメーターとしてCSRFトークンを見つけるため、このミドルウェアはJavaScriptのフレームワークで一般的に使用されている、X-XSRF-TOKENリクエストヘッダーもチェックします。例えば、"meta"タグの中にこのトークンを設置できます。送信前にjQueryを利用しヘッダーに付け加えてみましょう。In addition to looking for the CSRF token as a "POST" parameter, the middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a "meta" tag and instruct jQuery to add it to all request headers:
<meta name="csrf-token" content="{{ csrf_token() }}" />
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
これで、全AJAXリクエストは自動的にCSRFトークンを含むようになります。Now all AJAX requests will automatically include the CSRF token:
$.ajax({
url: "/foo/bar",
})
X-XSRF-TOKENX-XSRF-TOKEN
Laravelはさらに、XSRF-TOKENクッキーの中にCSRFトークンを保存します。このクッキーの値をX-XSRF-TOKENリクエストヘッダーに設定するために利用できます。AngularのようないくつかのJavaScriptフレームワークでは、自動的に行われます。Laravel also stores the CSRF token in a XSRF-TOKEN cookie. You can use the cookie value to set the X-XSRF-TOKEN request header. Some JavaScript frameworks, like Angular, do this automatically for you.
メモ:
X-CSRF-TOKENとX-XSRF-TOKENの違いは、前者が平文の値に使用されるのに対し、後者は暗号化された値で使用します。Laravelではクッキーは常に暗号化されるため、後者を使用しています。トークンの値を与えるためにcsrf_token()関数を使っている場合は、X-CSRF-TOKENヘッダーを使用する必要が多分あるでしょう。Note: The difference between theX-CSRF-TOKENandX-XSRF-TOKENis that the first uses a plain text value and the latter uses an encrypted value, because cookies in Laravel are always encrypted. If you use thecsrf_token()function to supply the token value, you probably want to use theX-CSRF-TOKENheader.
擬似メソッドMethod Spoofing
HTMLフォームはPUTとPATCH、DELETEアクションをサポートしていません。ですから、PUT、PATCH、DELETEのルートを呼び出すHTMLフォームを定義している場合、_method隠しフィールドをそのフォームに追加する必要があります。HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form.
_methodフィールドで送る値は、HTTPリクエストのメソッドとして使用されます。例をご覧ください。The value sent with the _method field will be used as the HTTP request method. For example:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
</form>
ルートパラメーターRoute Parameters
もちろんルート中にある、リクエストURIのセグメントを取得することもできます。Of course, you can capture segments of the request URI within your route:
基本的なルートパラメーターBasic Route Parameter
Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
注意: ルートパラメーターに
-を含めることはできません。代わりに下線(_)を使ってください。Note: Route parameters cannot contain the-character. Use an underscore (_) instead.
オプションのルートパラメーターOptional Route Parameters
Route::get('user/{name?}', function($name = null)
{
return $name;
});
デフォルト値を指定したオプションのルートパラメーターOptional Route Parameters With Default Value
Route::get('user/{name?}', function($name = 'John')
{
return $name;
});
正規表現によるルートの束縛Regular Expression Parameter Constraints
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
Route::get('user/{id}', function($id)
{
//
})
->where('id', '[0-9]+');
正規表現の配列による束縛Passing An Array Of Constraints
Route::get('user/{id}/{name}', function($id, $name)
{
//
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
グローバルパターンの定義Defining Global Patterns
patternメソッドを使用すれば、ルートパラメーターを指定した正規表現で常に束縛することができます。これらは、RouteServiceProviderのbootメソッドで定義することを推奨します。If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method. You should define these patterns in the boot method of your RouteServiceProvider:
$router->pattern('id', '[0-9]+');
パターンが定義されると、そのパラメーターを使用する全ルートに適用されます。Once the pattern has been defined, it is applied to all routes using that parameter:
Route::get('user/{id}', function($id)
{
// Only called if {id} is numeric.
});
ルートパラメーター値へのアクセスAccessing A Route Parameter Value
ルートの外で、ルートパラメーターの値にアクセスする必要がある場合、inputメソッドが使用できます。If you need to access a route parameter value outside of a route, use the input method:
if ($route->input('id') == 1)
{
//
}
また、現在のルートパラメーターへは、Illuminate\Http\Requestインスタンスによってもアクセスできます。現在のリクエストのリクエストインスタンスは、Requestファサードや、依存が注入される場所でIlluminate\Http\Requestをタイプヒントで指定することによってもアクセス可能です。You may also access the current route parameters via the Illuminate\Http\Request instance. The request instance for the current request may be accessed via the Request facade, or by type-hinting the Illuminate\Http\Request where dependencies are injected:
use Illuminate\Http\Request;
Route::get('user/{id}', function(Request $request, $id)
{
if ($request->route('id'))
{
//
}
});
名前付きルートNamed Routes
リダイレクトやURLを生成する場合により便利にするために、ルートにつけた名前によりルートを参照することができます。ルート名を配列キーのasで定義してください。Named routes allow you to conveniently generate URLs or redirects for a specific route. You may specify a name for a route with the as array key:
Route::get('user/profile', ['as' => 'profile', function()
{
//
}]);
コントローラアクションに対してもルート名を指定できます。You may also specify route names for controller actions:
Route::get('user/profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
これで、ルート名をURLやリダイレクトを生成する場合に使用できます。Now, you may use the route's name when generating URLs or redirects:
$url = route('profile');
$redirect = redirect()->route('profile');
実行中のルート名はcurrentRouteNameメソッドでアクセスできます。The currentRouteName method returns the name of the route handling the current request:
$name = Route::currentRouteName();
ルートグループRoute Groups
URLセグメント、ミドルウェア、名前空間など、多くのルートで同じ共通の制約・設定を行いたい場合があります。全てのルートにこうしたオプションを個別に指定する代わりに、まとめてルートへ属性を適用できるルートグループが使用できます。Sometimes many of your routes will share common requirements such as URL segments, middleware, namespaces, etc. Instead of specifying each of these options on every route individually, you may use a route group to apply attributes to many routes.
共通の属性は、Route::groupメソッドの最初の引数として配列で指定します。Shared attributes are specified in an array format as the first parameter to the Route::group method.
ミドルウェアMiddleware
グループの全ルートへミドルウェアを適用するには、属性配列の中のmiddleware引数を指定し、ミドルウェアのリストを定義してください。この配列に指定された順番で、ミドルウェアが実行されます。Middleware are applied to all routes within the group by defining the list of middleware with the middleware parameter on the group attribute array. Middleware will be executed in the order you define this array:
Route::group(['middleware' => ['foo', 'bar']], function()
{
Route::get('/', function()
{
// FooとBarミドルウェア適用
});
Route::get('user/profile', function()
{
// FooとBarミドルウェア適用
});
});
名前空間Namespaces
グループ中の全コントローラーへ名前空間を指定するには、グループ属性配列中にnamespace引数を使用します。You may use the namespace parameter in your group attribute array to specify the namespace for all controllers within the group:
Route::group(['namespace' => 'Admin'], function()
{
// "App\Http\Controllers\Admin"名前空間のコントローラー
Route::group(['namespace' => 'User'], function()
{
// "App\Http\Controllers\Admin\User"名前空間のコントローラー
});
});
注意: デフォルトで
RouteServiceProviderが名前空間グループを含むroutes.phpファイルを読み込んでいるので、完全な名前空間の先頭からApp\\Http\\Controllersを除いてコントローラールートを登録できます。Note: By default, theRouteServiceProviderincludes yourroutes.phpfile within a namespace group, allowing you to register controller routes without specifying the fullApp\Http\Controllersnamespace prefix.
サブドメインルーティングSub-Domain Routing
Laravelのルートではサブドメインをワイルドカードで処理でき、ドメイン名のワイルドカードパラメーターをルートに渡すことも可能です。Laravel routes also handle wildcard sub-domains, and will pass your wildcard parameters from the domain:
サブドメインルートの登録Registering Sub-Domain Routes
Route::group(['domain' => '{account}.myapp.com'], function()
{
Route::get('user/{id}', function($account, $id)
{
//
});
});
ルートのプレフィックスRoute Prefixing
ルートグループのプレフィックスはグループの属性配列でprefixオプションを使用し指定します。A group of routes may be prefixed by using the prefix option in the attributes array of a group:
Route::group(['prefix' => 'admin'], function()
{
Route::get('users', function()
{
// "/admin/users"のURLと一致
});
});
さらに、ルートへ共通のパラメーターを渡すために、prefixパラメーターを利用することもできます。You can also utilize the prefix parameter to pass common parameters to your routes:
ルートプレフィックス中でURLパラメーターの登録Registering a URL parameter in a route prefix
Route::group(['prefix' => 'accounts/{account_id}'], function()
{
Route::get('detail', function($account_id)
{
//
});
});
プレフィックス中で名前をつけたパラメーターに対し、制約を指定することも可能です。You can even define parameter constraints for the named parameters in your prefix:
Route::group([
'prefix' => 'accounts/{account_id}',
'where' => ['account_id' => '[0-9]+'],
], function() {
// ここでルートを定義する
});
ルートとモデルの結合Route Model Binding
Laravelモデル結合は、モデルのインスタンスをルートから受け取る、便利な手法です。例えば、ユーザーのIDを受け取る代わりに、そのIDに合致するUserモデルのインスタンスを受け取ることができます。Laravel model binding provides a convenient way to inject class instances into your routes. For example, instead of injecting a user's ID, you can inject the entire User class instance that matches the given ID.
最初に、ルーターのmodelメソッドで指定したパラメーターで使用するモデルを指定します。モデルの結合は、RouteServiceProvider::bootメソッドの中で定義してください。First, use the router's model method to specify the class for a given parameter. You should define your model bindings in the RouteServiceProvider::boot method:
モデルとパラメーターを結合するBinding A Parameter To A Model
public function boot(Router $router)
{
parent::boot($router);
$router->model('user', 'App\User');
}
次に、{user}パラメーターを含んだルートを定義します。Next, define a route that contains a {user} parameter:
Route::get('profile/{user}', function(App\User $user)
{
//
});
{user}パラメーターとUserモデルを結合済みですから、ルートからUserインスタンスが渡されます。例えば、profile/1がリクエストされると、IDが1のUserインスタンスが渡されます。Since we have bound the {user} parameter to the App\User model, a User instance will be injected into the route. So, for example, a request to profile/1 will inject the User instance which has an ID of 1.
**注目:**もしデータベースにモデルのインスタンスが見つからない場合、404エラーがスローされますNote: If a matching model instance is not found in the database, a 404 error will be thrown.
もし独自の"not found"動作を指定したい場合は、modelメソッドへクロージャーを3つ目の引数として渡してください。If you wish to specify your own "not found" behavior, pass a Closure as the third argument to the model method:
Route::model('user', 'User', function()
{
throw new NotFoundHttpException;
});
独自のインスタンス取得ロジックを実装したい場合は、Route::bindメソッドを使用してください。bindメソッドのクロージャーには、URIセグメントの値が渡されますので、ルートへ注入したいクラスのインスタンスを返してください。If you wish to use your own resolution logic, you should use the Route::bind method. The Closure you pass to the bind method will receive the value of the URI segment, and should return an instance of the class you want to be injected into the route:
Route::bind('user', function($value)
{
return User::where('name', $value)->first();
});
404エラーのthrowThrowing 404 Errors
手動で404エラーをルートから発生させるには2つの手法があります。最初の方法はabortヘルパを使用するものです。There are two ways to manually trigger a 404 error from a route. First, you may use the abort helper:
abort(404);
abortヘルパはただ、Symfony\Component\HttpKernel\Exception\HttpException例外を指定したステータスコードと共に投げる(throw)だけです。The abort helper simply throws a Symfony\Component\HttpKernel\Exception\HttpException with the specified status code.
2つめの方法はSymfony\Component\HttpKernel\Exception\NotFoundHttpExceptionのインスタンスを投げる方法です。Secondly, you may manually throw an instance of Symfony\Component\HttpKernel\Exception\NotFoundHttpException.
404例外の取り扱いやエラーのカスタム処理を行う詳しい方法は、ドキュメントのエラーの章をご覧ください。More information on handling 404 exceptions and using custom responses for these errors may be found in the errors[/docs/{{version}}/errors#http-exceptions] section of the documentation.