Readouble

Laravel 8.x HTTPレスポンス

レスポンスの生成Creating Responses

文字列と配列Strings & Arrays

当然ながらすべてのルートやコントローラは、ユーザーのブラウザに対し、何らかのレスポンスを返す必要があります。Laravelはレスポンスを返すためにさまざまな手段を用意しています。一番基本的なレスポンスは、ルートかコントローラから文字列を返します。フレームワークが自動的に、文字列を完全なHTTPレスポンスへ変換します。All routes and controllers should return a response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

Route::get('/', function () {
    return 'Hello World';
});

ルートやコントローラから文字列を返す他に、配列も返せます。フレームワークは自動的に、配列をJSONレスポンスへ変換します。In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Route::get('/', function () {
    return [1, 2, 3];
});

lightbulb">Tip!! Eloquentコレクションも返せることを知っていますか? 自動的にJSONへ変換されます。試してください!{tip} Did you know you can also return Eloquent collections[/docs/{{version}}/eloquent-collections] from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

レスポンスオブジェクトResponse Objects

通常、皆さんは単純な文字列や配列をルートアクションから返すだけじゃありませんよね。代わりに、Illuminate\Http\Responseインスタンスかビューを返したいですよね。Typically, you won't just be returning simple strings or arrays from your route actions. Instead, you will be returning full Illuminate\Http\Response instances or views[/docs/{{version}}/views].

完全なResponseインスタンスを返せば、レスポンスのHTTPステータスコードやヘッダをカスタマイズできます。Responseインスタンスは、Symfony\Component\HttpFoundation\Responseクラスを継承しており、HTTPレスポンスを構築するためにさまざまなメソッドを提供しています。Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, which provides a variety of methods for building HTTP responses:

Route::get('/home', function () {
    return response('Hello World', 200)
                  ->header('Content-Type', 'text/plain');
});

EloquentモデルとコレクションEloquent Models & Collections

Eloquent ORMモデルとコレクションをルートとコントローラから直接返すこともできます。これを行うと、Laravelはモデルの非表示属性を尊重しながら、モデルやコレクションをJSONレスポンスへ自動的に変換します。You may also return Eloquent ORM[/docs/{{version}}/eloquent] models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model's hidden attributes[/docs/{{version}}/eloquent-serialization#hiding-attributes-from-json]:

use App\Models\User;

Route::get('/user/{user}', function (User $user) {
    return $user;
});

レスポンスへのヘッダ付加Attaching Headers To Responses

レスポンスインスタンスをスラスラと構築できるように、ほとんどのレスポンスメソッドはチェーンとしてつなげられることを覚えておきましょう。たとえば、ユーザーにレスポンスを送り返す前に、headerメソッドでいくつかのヘッダを追加できます。Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');

もしくは、withHeadersメソッドで、レスポンスへ追加したいヘッダの配列を指定します。Or, you may use the withHeaders method to specify an array of headers to be added to the response:

return response($content)
            ->withHeaders([
                'Content-Type' => $type,
                'X-Header-One' => 'Header Value',
                'X-Header-Two' => 'Header Value',
            ]);

キャッシュコントロール・ミドルウェアCache Control Middleware

ルートグループへCache-Controlヘッダを簡単に指定できるよう、Laravelはcache.headersを用意しています。ディレクティブは、対応するcache-controlディレクティブの「スネークケース」を使用し、セミコロンで区切って指定してください。ディレクティブのリストの中でetagを指定すると、レスポンスコンテンツのMD5ハッシュをETag識別子へ自動的にセットします。Laravel includes a cache.headers middleware, which may be used to quickly set the Cache-Control header for a group of routes. Directives should be provided using the "snake case" equivalent of the corresponding cache-control directive and should be separated by a semicolon. If etag is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function () {
    Route::get('/privacy', function () {
        // ...
    });

    Route::get('/terms', function () {
        // ...
    });
});

レスポンスへのクッキー付加Attaching Cookies To Responses

cookieメソッドを使用して、発信Illuminate\Http\Responseインスタンスへクッキーを添付できます。Cookieが有効であると見なされる名前、値、および分数をメソッドへ渡す必要があります。You may attach a cookie to an outgoing Illuminate\Http\Response instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

return response('Hello World')->cookie(
    'name', 'value', $minutes
);

cookieメソッドはさらに、使用機会が少ない引数をいくつか受け付けます。これらの引数は、全般的にPHPネイティブのsetcookieメソッドに指定する引数と、同じ目的、同じ意味合いを持っています。The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP's native setcookie[https://secure.php.net/manual/en/function.setcookie.php] method:

return response('Hello World')->cookie(
    'name', 'value', $minutes, $path, $domain, $secure, $httpOnly
);

クッキーが送信レスポンスとともに確実に送信したいが、そのレスポンスのインスタンスがまだない場合は、Cookieファサードを使用して、送信時にレスポンスへ添付するためにそのクッキーを「キュー」へ投入できます。queueメソッドは、クッキーインスタンスの作成に必要な引数をとります。こうしたクッキーは、ブラウザへ送信される前に送信レスポンスへ添付します。If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to "queue" cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

use Illuminate\Support\Facades\Cookie;

Cookie::queue('name', 'value', $minutes);

クッキーインスタンスの生成Generating Cookie Instances

後ほどレスポンスインスタンスへアタッチできるSymfony\Component\HttpFoundation\Cookieインスタンスを生成したい場合は、グローバルなcookieヘルパを使用します。このCookieは、レスポンスインスタンスへ添付しない限り、クライアントに返送されません。If you would like to generate a Symfony\Component\HttpFoundation\Cookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

$cookie = cookie('name', 'value', $minutes);

return response('Hello World')->cookie($cookie);

クッキーの早期期限切れExpiring Cookies Early

送信レスポンスのwithoutCookieメソッドを介してクッキーを期限切れにすることにより、そのクッキーを削除できます。You may remove a cookie by expiring it via the withoutCookie method of an outgoing response:

return response('Hello World')->withoutCookie('name');

送信レスポンスのインスタンスがまだない場合は、Cookieファサードのexpireメソッドを使用してCookieを期限切れにすることができます。If you do not yet have an instance of the outgoing response, you may use the Cookie facade's expire method to expire a cookie:

Cookie::expire('name');

クッキーと暗号化Cookies & Encryption

Laravelにより生成されるクッキーは、クライアントにより変更されたり、読まれたりされないようにデフォルトで暗号化され、署名されます。アプリケーションで生成する特定のクッキーで暗号化を無効にしたい場合は、app/Http/Middlewareディレクトリ中に存在する、App\Http\Middleware\EncryptCookiesミドルウェアの$exceptプロパティで指定してください。By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the App\Http\Middleware\EncryptCookies middleware, which is located in the app/Http/Middleware directory:

/**
 * 暗号化しないクッキー名
 *
 * @var array
 */
protected $except = [
    'cookie_name',
];

リダイレクトRedirects

リダイレクトのレスポンスはIlluminate\Http\RedirectResponseクラスのインスタンスであり、ユーザーを他のURLへリダイレクトさせるために必要なしっかりとしたヘッダを含んでいます。RedirectResponseインスタンスを生成するにはさまざまな方法があります。一番簡単な方法は、グローバルなredirectヘルパを使う方法です。Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

Route::get('/dashboard', function () {
    return redirect('home/dashboard');
});

送信したフォームが無効な場合など、ユーザーを以前の場所にリダイレクトしたい場合があります。これは、グローバルなbackヘルパ関数を使用して行うことができます。この機能はセッションを利用するため、back関数を呼び出すルートがwebミドルウェアグループを使用していることを確認してください。Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session[/docs/{{version}}/session], make sure the route calling the back function is using the web middleware group:

Route::post('/user/profile', function () {
    // レスポンスのバリデーション処理…

    return back()->withInput();
});

名前付きルートへのリダイレクトRedirecting To Named Routes

redirectヘルパを引数無しで呼ぶと、Illuminate\Routing\Redirectorインスタンスが返され、Redirectorインスタンスのメソッドが呼び出せるようになります。たとえば、名前付きルートに対するRedirectResponseを生成したい場合は、routeメソッドが使えます。When you call the redirect helper with no parameters, an instance of Illuminate\Routing\Redirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:

return redirect()->route('login');

ルートにパラメーターがある場合は、routeメソッドの第2引数として渡してください。If your route has parameters, you may pass them as the second argument to the route method:

// /profile/{id}のURIを持つルートの場合

return redirect()->route('profile', ['id' => 1]);

Eloquentモデルによる、パラメータの埋め込みPopulating Parameters Via Eloquent Models

Eloquentモデルの"ID"をルートパラメーターとしてリダイレクトする場合は、モデルをそのまま渡してください。IDは自動的にとり出されます。If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:

//  /profile/{id}のURIを持つルートの場合

return redirect()->route('profile', [$user]);

ルートパラメータへ配置する値をカスタマイズする場合は、ルートパラメータ定義(/profile/{id:slug})でカラムを指定するか、EloquentモデルのgetRouteKeyメソッドをオーバーライドします。If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (/profile/{id:slug}) or you can override the getRouteKey method on your Eloquent model:

/**
 * モデルのルートキー値の取得
 *
 * @return mixed
 */
public function getRouteKey()
{
    return $this->slug;
}

コントローラアクションへのリダイレクトRedirecting To Controller Actions

コントローラアクションに対するリダイレクトを生成することもできます。そのためには、コントローラとアクションの名前をactionメソッドに渡してください。You may also generate redirects to controller actions[/docs/{{version}}/controllers]. To do so, pass the controller and action name to the action method:

use App\Http\Controllers\UserController;

return redirect()->action([UserController::class, 'index']);

コントローラルートにパラメーターが必要ならば、actionメソッドの第2引数として渡してください。If your controller route requires parameters, you may pass them as the second argument to the action method:

return redirect()->action(
    [UserController::class, 'profile'], ['id' => 1]
);

外部ドメインへのリダイレクトRedirecting To External Domains

アプリケーション外のドメインへリダイレクトする必要がときどき起きます。このためにはawayメソッドを呼び出してください。これはRedirectResponseを生成しますが、URLエンコードを追加せず、バリデーションも検証も行いません。Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

return redirect()->away('https://www.google.com');

フラッシュデータを保存するリダイレクトRedirecting With Flashed Session Data

新しいURLへリダイレクトし、セッションへフラッシュデータを保存するのは、一度にまとめて行われる典型的な作業です。典型的な使い方は、あるアクションが実行成功した後に、実効成功メッセージをフラッシュデータとしてセッションに保存する場合でしょう。これに便利なように、RedirectResponseインスタンスを生成し、メソッドチェーンを一つだけさっと書けば、データをセッションへ保存できるようになっています。Redirecting to a new URL and flashing data to the session[/docs/{{version}}/session#flash-data] are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

Route::post('/user/profile', function () {
    // …

    return redirect('dashboard')->with('status', 'Profile updated!');
});

ユーザーを新しいページヘリダイレクトした後、セッションへ保存したフラッシュデータのメッセージを取り出して、表示します。たとえば、Blade記法を使ってみましょう。After the user is redirected, you may display the flashed message from the session[/docs/{{version}}/session]. For example, using Blade syntax[/docs/{{version}}/blade]:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

入力と共にリダイレクトRedirecting With Input

ユーザーを新しい場所にリダイレクトする前に、RedirectResponseインスタンスが提供するwithInputメソッドを使用して、現在のリクエストの入力データをセッションへ一時保存できます。これは通常、ユーザーがバリデーションエラーに遭遇した場合に行います。入力をセッションに一時保存したら、次のリクエスト中で簡単に取得してフォームを再入力できます。You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it[/docs/{{version}}/requests#retrieving-old-input] during the next request to repopulate the form:

return back()->withInput();

他のレスポンスタイプOther Response Types

responseヘルパは、他のタイプのレスポンスインスタンスを生成するために便利です。responseヘルパが引数なしで呼び出されると、Illuminate\Contracts\Routing\ResponseFactory契約が返されます。この契約はレスポンスを生成するための、さまざまなメソッドを提供しています。The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the Illuminate\Contracts\Routing\ResponseFactory contract[/docs/{{version}}/contracts] is returned. This contract provides several helpful methods for generating responses.

ViewレスポンスView Responses

レスポンスのステータスやヘッダをコントロールしながらも、レスポンス内容としてビューを返す必要がある場合は、viewメソッドを使用してください。If you need control over the response's status and headers but also need to return a view[/docs/{{version}}/views] as the response's content, you should use the view method:

return response()
            ->view('hello', $data, 200)
            ->header('Content-Type', $type);

もちろん、カスタムHTTPステータスコードやカスタムヘッダを渡す必要がない場合は、グローバルなviewヘルパ関数が使用できます。Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global view helper function.

JSONレスポンスJSON Responses

jsonメソッドは自動的にContent-Typeヘッダをapplication/jsonにセットし、同時に指定された配列をjson_encode PHP関数によりJSONへ変換します。The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA',
]);

JSONPレスポンスを生成したい場合は、jsonメソッドとwithCallbackメソッドを組み合わせてください。If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:

return response()
            ->json(['name' => 'Abigail', 'state' => 'CA'])
            ->withCallback($request->input('callback'));

FileダウンロードFile Downloads

downloadメソッドを使用して、ユーザーのブラウザに対し、指定パスのファイルをダウンロードするように強制するレスポンスを生成できます。downloadメソッドは、メソッドの引数の2番目にファイル名を取ります。これにより、ユーザーがファイルをダウンロードするときに表示するファイル名が決まります。最後に、HTTPヘッダの配列をメソッドの3番目の引数として渡すこともできます。The download method may be used to generate a response that forces the user's browser to download the file at the given path. The download method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

Note: note ファイルダウンロードを管理しているSymfony HttpFoundationクラスは、ASCIIのダウンロードファイル名を指定するよう要求しています。{note} Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename.

ストリームダウンロードStreamed Downloads

特定の操作の文字列レスポンスを、操作の内容をディスクに書き込まずにダウンロード可能なレスポンスへ変換したい場合もあるでしょう。このシナリオでは、streamDownloadメソッドを使用します。このメソッドは、コールバック、ファイル名、およびオプションのヘッダ配列を引数に取ります。Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments:

use App\Services\GitHub;

return response()->streamDownload(function () {
    echo GitHub::api('repo')
                ->contents()
                ->readme('laravel', 'laravel')['contents'];
}, 'laravel-readme.md');

FileレスポンスFile Responses

fileメソッドは、ダウンロードする代わりに、ブラウザへ画像やPDFのようなファイルを表示するために使用します。このメソッドは第1引数にファイルパス、第2引数にヘッダの配列を指定します。The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

レスポンスマクロResponse Macros

さまざまなルートやコントローラで再利用できるカスタムレスポンスを定義する場合は、Responseファサードでmacroメソッドを使用してください。通常、このメソッドは、App\Providers\AppServiceProviderサービスプロバイダなど、アプリケーションのサービスプロバイダの1つのbootメソッドから呼び出す必要があります。If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade. Typically, you should call this method from the boot method of one of your application's service providers[/docs/{{version}}/providers], such as the App\Providers\AppServiceProvider service provider:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * 全アプリケーションサービスの初期起動処理
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('caps', function ($value) {
            return Response::make(strtoupper($value));
        });
    }
}

macro関数は、最初の引数に名前を受け入れ、2番目の引数にクロージャを取ります。マクロのクロージャは、ResponseFactory実装またはresponseヘルパからマクロ名を呼び出すときに実行されます。The macro function accepts a name as its first argument and a closure as its second argument. The macro's closure will be executed when calling the macro name from a ResponseFactory implementation or the response helper:

return response()->caps('foo');

章選択

設定

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

ヘッダー項目移動

キーボード操作