Readouble

Laravel 5.dev HTTPルーティング

基本的なルーティング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

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/master/templating]:

<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/master/middleware] will verify token in the request input matches the token stored in the session.

さらに、"POST"パラメーターとしてCSRFトークンを見つけるため、このミドルウェアはJavascriptのフレームワークで一般的に使用されている、X-XSRF-TOKENリクエストヘッダーもチェックします。In addition to looking for the CSRF token as a "POST" parameter, the middleware will also check for the X-XSRF-TOKEN request header, which is commonly used by JavaScript frameworks.

擬似メソッドMethod Spoofing

HTMLフォームはPUTDELETEアクションをサポートしていません。ですから、PUTDELETEのルートを呼び出すHTMLフォームを定義している場合、_method隠しフィールドをそのフォームに追加する必要があります。HTML forms do not support PUT or DELETE actions. So, when defining PUT 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;
});

オプションのルートパラメーター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メソッドを使用すれば、ルートパラメーターを指定した正規表現で常に束縛することができます。これらは、RouteServiceProviderbeforeメソッドで定義することを推奨します。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 before 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

フィルターをルートのグループに対して使用する必要がある場合もあるでしょう。それぞれのルートにフィルターを個別に指定する代わりに、ルートグループを使用できます。Sometimes you may need to apply filters to a group of routes. Instead of specifying the filter on each route, you may use a route group:

Route::group(['before' => 'auth'], function()
{
	Route::get('/', function()
	{
		// Authフィルター適用
	});

	Route::get('user/profile', function()
	{
		// Authフィルター適用
	});
});

またgroupの配列へ、namespace引数により、そのグループのコントローラー全部に対し、名前空間を指定することもできます。You may use the namespace parameter within your group array to specify the namespace for all controllers within the group:

Route::group(['namespace' => 'Admin'], function()
{
	//
});

注目: デフォルトでRouteServiceProviderは、名前空間グループの中でroutes.phpファイルを呼び出します。これにより、完全な名前空間を指定せずに、コントローラールートが登録できます。Note: By default, the RouteServiceProvider includes your routes.php file within a namespace group, allowing you to register controller routes without specifying the full namespace.

サブドメインルーティング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('user', 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;
});

独自のインスタンス取得ロジックを使用したい場合は、Router::bindメソッドを使用してください。bindメソッドのクロージャーには、URIセグメントの値が渡されますので、ルートへ注入したいクラスのインスタンスを返してください。If you wish to use your own resolution logic, you should use the Router::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エラーのスローThrowing 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\HttpFoundation\Exception\HttpException例外を指定したステータスコードと共にスローするだけです。The abort helper simply throws a Symfony\Component\HttpFoundation\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/master/errors#http-exceptions] section of the documentation.

章選択

Artisan CLI

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作