Readouble

Laravel 5.7 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インスタンスかviewsを返したいですよね。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');
});

ヘッダの付加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',
            ]);

クッキーの付加Attaching Cookies To Responses

レスポンスインスタンスのcookieメソッドで、レスポンスへ簡単にクッキーを付加できます。たとえば、cookieメソッドでクッキーを生成し、レスポンスインスタンスへ、さっと付加してみましょう。The cookie method on response instances allows you to easily attach cookies to the response. For example, you may use the cookie method to generate a cookie and fluently attach it to the response instance like so:

return response($content)
                ->header('Content-Type', $type)
                ->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:

->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)

もしくは、アプリケーションから送り出すレスポンスへアタッチするクッキーを「キュー」するために、Cookieファサードが使えます。queueメソッドは、CookieインスタンスかCookieインスタンスを生成するために必要な引数を受け取ります。こうしたクッキーは、ブラウザにレスポンスが送信される前にアタッチされます。Alternatively, you can use the Cookie facade to "queue" cookies for attachment to the outgoing response from your application. The queue method accepts a Cookie instance or the arguments needed to create a Cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

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

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

クッキーと暗号化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 or has all of the session middleware applied:

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]);

ルートパラメータに埋め込む値をカスタマイズしたい場合は、EloquentモデルのgetRouteKeyメソッドをオーバーライドします。If you would like to customize the value that is placed in the route parameter, you should override the getRouteKey method on your Eloquent model:

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

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

コントローラアクションに対するリダイレクトを生成することもできます。そのためには、コントローラとアクションの名前をactionメソッドに渡してください。LaravelのRouteServiceProviderにより、ベースのコントローラ名前空間が自動的に設定されるため、コントローラの完全名前空間名を指定する必要がないことを覚えておいてください。You may also generate redirects to controller actions[/docs/{{version}}/controllers]. To do so, pass the controller and action name to the action method. Remember, you do not need to specify the full namespace to the controller since Laravel's RouteServiceProvider will automatically set the base controller namespace:

return redirect()->action('HomeController@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@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

他のレスポンスタイプ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 should 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引数として受け取り、ユーザーがダウンロードするファイル名になります。第3引数にHTTPヘッダの配列を渡すこともできます。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 file name as the second argument to the method, which will determine the file name 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);

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

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

ストリームダウンロード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, file name, and an optional array of headers as its arguments:

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メソッドが使用できます。たとえば、サービスプロバイダ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. For example, from a service provider's[/docs/{{version}}/providers] boot method:

<?php

namespace App\Providers;

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

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションのレスポンスマクロ登録
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('caps', function ($value) {
            return Response::make(strtoupper($value));
        });
    }
}

macroメソッドは登録名を第1引数、クロージャを第2引数に取ります。マクロのクロージャはResponseFactoryの実装か、responseヘルパに対し、登録名で呼び出すことで、実行されます。The macro function accepts a name as its first argument, and a Closure as its second. 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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作