Readouble

Laravel 8.x URL生成

イントロダクションIntroduction

Laravelは、アプリケーションのURLを生成するのに役立つヘルパをいくつか提供しています。これらのヘルパは、主にテンプレートとAPIレスポンスでリンクを構築するとき、またはアプリケーションの別の部分へのリダイレクトレスポンスを生成するときに役立ちます。Laravel provides several helpers to assist you in generating URLs for your application. These helpers are primarily helpful when building links in your templates and API responses, or when generating redirect responses to another part of your application.

基礎The Basics

URLの生成Generating URLs

urlヘルパは、アプリケーションの任意のURLを生成するために使用します。生成したURLは、アプリケーションが処理している現在のリクエストのスキーム(HTTPまたはHTTPS)とホストを自動的に使用します。The url helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current request being handled by the application:

$post = App\Models\Post::find(1);

echo url("/posts/{$post->id}");

// http://example.com/posts/1

現在のURLへのアクセスAccessing The Current URL

urlヘルパにパスを指定しないと、Illuminate\Routing\UrlGeneratorインスタンスが返され、現在のURLに関する情報へアクセスできます。If no path is provided to the url helper, an Illuminate\Routing\UrlGenerator instance is returned, allowing you to access information about the current URL:

// クエリ文字列を除いた現在のURL
echo url()->current();

// クエリ文字列を含んだ現在のURL
echo url()->full();

// 直前のリクエストの完全なURL
echo url()->previous();

こうしたメソッドには、URLファサードを使用してもアクセスできます。Each of these methods may also be accessed via the URL facade[/docs/{{version}}/facades]:

use Illuminate\Support\Facades\URL;

echo URL::current();

名前付きルートのURLURLs For Named Routes

routeヘルパは、名前付きルートへのURLを生成するためにも使用できます。名前付きルートを使用すると、ルートで定義する実際のURLと結合せずにURLを生成できます。したがって、ルートのURLが変更された場合でも、route関数の呼び出しを変更する必要はありません。たとえば、アプリケーションに次のように定義されたルートが含まれているとします。The route helper may be used to generate URLs to named routes[/docs/{{version}}/routing#named-routes]. Named routes allow you to generate URLs without being coupled to the actual URL defined on the route. Therefore, if the route's URL changes, no changes need to be made to your calls to the route function. For example, imagine your application contains a route defined like the following:

Route::get('/post/{post}', function (Post $post) {
    //
})->name('post.show');

このルートへのURLを生成するには、次のようにrouteヘルパを使用します。To generate a URL to this route, you may use the route helper like so:

echo route('post.show', ['post' => 1]);

// http://example.com/post/1

もちろん、routeヘルパを使用して、複数のパラメーターを持つルートのURLを生成することもできます。Of course, the route helper may also be used to generate URLs for routes with multiple parameters:

Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) {
    //
})->name('comment.show');

echo route('comment.show', ['post' => 1, 'comment' => 3]);

// http://example.com/post/1/comment/3

ルートの定義パラメータに対応しない過剰な配列要素は、URLのクエリ文字列として追加されます。Any additional array elements that do not correspond to the route's definition parameters will be added to the URL's query string:

echo route('post.show', ['post' => 1, 'search' => 'rocket']);

// http://example.com/post/1?search=rocket

Eloquent ModelsEloquent Models

Eloquentモデルのルートキー(通常は主キー)を使ってURLを生成することが多いでしょう。そのため、パラメータ値としてEloquentモデルを渡せます。routeヘルパは、モデルのルートキーを自動的に抽出します。You will often be generating URLs using the route key (typically the primary key) of Eloquent models[/docs/{{version}}/eloquent]. For this reason, you may pass Eloquent models as parameter values. The route helper will automatically extract the model's route key:

echo route('post.show', ['post' => $post]);

署名付きURLSigned URLs

Laravelでは名前付きルートに対し、簡単に「署名付きURL」を作成できます。このURLは「署名」ハッシュをクエリ文字列として付加し、作成されてからそのURLが変更されていないかをLaravelで確認できるようにします。署名付きURLは公にアクセスさせるルートではあるが、URL操作に対する保護レイヤが必要な場合とくに便利です。Laravel allows you to easily create "signed" URLs to named routes. These URLs have a "signature" hash appended to the query string which allows Laravel to verify that the URL has not been modified since it was created. Signed URLs are especially useful for routes that are publicly accessible yet need a layer of protection against URL manipulation.

たとえば、公の「購読終了」リンクを顧客へのメールへ用意するために、署名付きURLが使用できます。名前付きルートに対し署名URLを作成するには、URLファサードのsignedRouteメソッドを使用します。For example, you might use signed URLs to implement a public "unsubscribe" link that is emailed to your customers. To create a signed URL to a named route, use the signedRoute method of the URL facade:

use Illuminate\Support\Facades\URL;

return URL::signedRoute('unsubscribe', ['user' => 1]);

指定する時間が経過すると期限切れになる一時的な署名付きルートURLを生成する場合は、temporarySignedRouteメソッドを使用します。Laravelが一時的な署名付きルートURLを検証するとき、署名付きURLにエンコードされている有効期限のタイムスタンプが経過していないことを確認します。If you would like to generate a temporary signed route URL that expires after a specified amount of time, you may use the temporarySignedRoute method. When Laravel validates a temporary signed route URL, it will ensure that the expiration timestamp that is encoded into the signed URL has not elapsed:

use Illuminate\Support\Facades\URL;

return URL::temporarySignedRoute(
    'unsubscribe', now()->addMinutes(30), ['user' => 1]
);

署名付きルートリクエストの検査Validating Signed Route Requests

送信されてきたリクエストが有効な署名を持っているかを検査するには、送信されたRequestに対して、hasValidSignatureメソッドを呼び出します。To verify that an incoming request has a valid signature, you should call the hasValidSignature method on the incoming Request:

use Illuminate\Http\Request;

Route::get('/unsubscribe/{user}', function (Request $request) {
    if (! $request->hasValidSignature()) {
        abort(401);
    }

    // ...
})->name('unsubscribe');

もしくは、Illuminate\Routing\Middleware\ValidateSignatureミドルウェアをルートに割り当てることもできます。このミドルウェアにHTTPカーネルのrouteMiddleware配列のキーを割り当てていない場合は、割り当てる必要があります。Alternatively, you may assign the Illuminate\Routing\Middleware\ValidateSignature middleware[/docs/{{version}}/middleware] to the route. If it is not already present, you should assign this middleware a key in your HTTP kernel's routeMiddleware array:

/**
 * アプリケーションルートのミドルウェア
 *
 * これらのミドルウェアはグループ、もしくは個別に指定される。
 *
 * @var array
 */
protected $routeMiddleware = [
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
];

ミドルウェアをカーネルに登録したら、それをルートにアタッチできます。受信リクエストに有効な署名がない場合、ミドルウェアは自動的に403HTTPレスポンスを返します。Once you have registered the middleware in your kernel, you may attach it to a route. If the incoming request does not have a valid signature, the middleware will automatically return a 403 HTTP response:

Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
})->name('unsubscribe')->middleware('signed');

無効な署名付きルートのレスポンスResponding To Invalid Signed Routes

期限切れになった署名付きURLを訪問すると、403 HTTPステータスコードの汎用エラーページが表示されます。ただし、例外ハンドラでInvalidSignatureException例外のカスタム"renderable"クロージャを定義することにより、この動作をカスタマイズできます。このクロージャはHTTPレスポンスを返す必要があります。When someone visits a signed URL that has expired, they will receive a generic error page for the 403 HTTP status code. However, you can customize this behavior by defining a custom "renderable" closure for the InvalidSignatureException exception in your exception handler. This closure should return an HTTP response:

use Illuminate\Routing\Exceptions\InvalidSignatureException;

/**
 * アプリケーションの例外処理コールバックの登録
 *
 * @return void
 */
public function register()
{
    $this->renderable(function (InvalidSignatureException $e) {
        return response()->view('error.link-expired', [], 403);
    });
}

コントローラアクションのURLURLs For Controller Actions

action関数は、指定するコントローラアクションに対するURLを生成します。The action function generates a URL for the given controller action:

use App\Http\Controllers\HomeController;

$url = action([HomeController::class, 'index']);

コントローラメソッドがルートパラメータを受け入れる場合、関数の2番目の引数としてルートパラメータの連想配列を渡せます。If the controller method accepts route parameters, you may pass an associative array of route parameters as the second argument to the function:

$url = action([UserController::class, 'profile'], ['id' => 1]);

デフォルト値Default Values

アプリケーションにより、特定のURLパラメータのデフォルト値をリクエスト全体で指定したい場合もあります。たとえば、多くのルートで{locale}パラメータを定義していると想像してください。For some applications, you may wish to specify request-wide default values for certain URL parameters. For example, imagine many of your routes define a {locale} parameter:

Route::get('/{locale}/posts', function () {
    //
})->name('post.index');

毎回routeヘルパを呼び出すごとに、localeをいつも指定するのは厄介です。そのため、現在のリクエストの間、常に適用されるこのパラメートのデフォルト値は、URL::defaultsメソッドを使用し定義できます。現在のリクエストでアクセスできるように、ルートミドルウェアから、このメソッドを呼び出したいかと思います。It is cumbersome to always pass the locale every time you call the route helper. So, you may use the URL::defaults method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a route middleware[/docs/{{version}}/middleware#assigning-middleware-to-routes] so that you have access to the current request:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    /**
     * 受信リクエストの処理
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Illuminate\Http\Response
     */
    public function handle($request, Closure $next)
    {
        URL::defaults(['locale' => $request->user()->locale]);

        return $next($request);
    }
}

一度localeパラメータに対するデフォルト値をセットしたら、routeヘルパを使いURLを生成する時に、値を渡す必要はもうありません。Once the default value for the locale parameter has been set, you are no longer required to pass its value when generating URLs via the route helper.

URLのデフォルトとミドルウェアの優先度URL Defaults & Middleware Priority

URLのデフォルト値を設定すると、Laravelの暗黙的なモデルバインディングの処理を妨げる可能性があります。したがって、URLのデフォルトをLaravel自身のSubstituteBindingsミドルウェアの前に実行するよう設定するため、ミドルウェアの優先度を設定する必要があります。それには、アプリケーションのHTTPカーネルの$middlewarePriorityプロパティ内にあるSubstituteBindingsミドルウェアの前にミドルウェアを確実に設置してください。Setting URL default values can interfere with Laravel's handling of implicit model bindings. Therefore, you should prioritize your middleware[/docs/{{version}}/middleware#sorting-middleware] that set URL defaults to be executed before Laravel's own SubstituteBindings middleware. You can accomplish this by making sure your middleware occurs before the SubstituteBindings middleware within the $middlewarePriority property of your application's HTTP kernel.

$middlewarePriorityプロパティはIlluminate\Foundation\Http\Kernelベースクラスで定義されています。変更するにはその定義をこのクラスからコピーし、アプリケーションのHTTPカーネルでオーバーライトしてください。The $middlewarePriority property is defined in the base Illuminate\Foundation\Http\Kernel class. You may copy its definition from that class and overwrite it in your application's HTTP kernel in order to modify it:

/**
 * ミドルウェアの優先リスト
 *
 * この指定により、グローバルではないミドルウェアは常にこの順番になります。
 *
 * @var array
 */
protected $middlewarePriority = [
    // ...
     \App\Http\Middleware\SetDefaultLocaleForUrls::class,
     \Illuminate\Routing\Middleware\SubstituteBindings::class,
     // ...
];

章選択

設定

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

ヘッダー項目移動

キーボード操作