Readouble

Laravel 5.2 HTTPレスポンス

基本のレスポンスBasic Responses

当然ながら全てのルートやコントローラーは、ユーザのブラウザーに対し、何らかのレスポンスを返す必要があります。Laravelはレスポンスを返すために様々な手段を用意しています。一番基本的なレスポンスは、ルートかコントローラーから単に文字列を返します。Of course, all routes and controllers should return some kind of response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is simply returning a string from a route or controller:

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

指定された文字列は、フレームワークによりHTTPレスポンスへ変換されます。The given string will automatically be converted into an HTTP response by the framework.

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

しかし通常、ほとんどのルートとコントローラーアクションからは、Illuminate\Http\Responseインスタンスか、ビューを返します。Responseインスタンスを返せば、レスポンスのHTTPステータスコードやヘッダがカスタマイズできます。Responseインスタンスは、Symfony\Component\HttpFoundation\Responseを継承しており、HTTPレスポンスを組み立てるために数多くのメソッドが提供されています。However, for most routes and controller actions, you will be returning a full Illuminate\Http\Response instance or a view[/docs/{{version}}/views]. 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, providing a variety of methods for building HTTP responses:

use Illuminate\Http\Response;

Route::get('home', function () {
    return (new Response($content, $status))
                  ->header('Content-Type', $value);
});

responseヘルパも、便利に使用できます。For convenience, you may also use the response helper:

Route::get('home', function () {
    return response($content, $status)
                  ->header('Content-Type', $value);
});

注意: Responseメソッドの完全なリストは, APIドキュメントSymfony API ドキュメントをご覧ください。Note: For a full list of available Response methods, check out its API documentation[http://laravel.com/api/master/Illuminate/Http/Response.html] and the Symfony API documentation[http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/Response.html].

ヘッダの付加Attaching Headers To Responses

レスポンスを速やかに組み立てられるようにほとんどのレスポンスメソッドは、チェーンとしてつなげられることを覚えておいてください。たとえば、ユーザにレスポンスを送り返す前に、headerメソッドでいくつかのヘッダを追加できます。Keep in mind that most response methods are chainable, allowing for the fluent building of responses. 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 helper method on the response instance allows you to easily attach cookies to the response. For example, you may use the cookie method to generate a cookie and attach it to the response instance:

return response($content)
                ->header('Content-Type', $type)
                ->cookie('name', 'value');

cookieメソッドはクッキーのプロパティーをカスタマイズするためのオプション引数を受け付けます。The cookie method accepts additional optional arguments which allow you to further customize your cookie's properties:

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

もしくは、Cookieファサードqueueメソッドを使い、レスポンスが送られる時点で自動的に付加されるクッキーを作成することもできます。Alternatively, you may use the queue method on the Cookie facade[/docs/{{version}}/facades] to create a cookie that will be automatically added to the outgoing response:

<?php

namespace App\Http\Controllers;

use Cookie;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    /**
     * アプリケーションダッシュボードの表示
     *
     * @return Response
     */
    public function index()
    {
        Cookie::queue('saw_dashboard', true, 15);

        return view('dashboard');
    }
}

この例の場合、saw_dashboardクッキーは、意図的にレスポンスインスタンスに添付するようにコードしなくても、レスポンスが返される時点で自動的にそのレスポンスへ追加されます。In this example, the saw_dashboard cookie will automatically be added to the outgoing response without forcing you to manually attach the cookie to a specific response instance.

クッキーと暗号化Cookies & Encryption

Laravelにより生成されるクッキーは、クライアントにより変更されたり読まれたりされないようにデフォルトで暗号化され、署名されます。アプリケーションで生成する特定のクッキーで暗号化を無効にしたい場合は、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 certain subset of cookies generated by your application, you may use the $except property of the App\Http\Middleware\EncryptCookies middleware:

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

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

responseヘルパは、他のタイプのレスポンスインスタンスを生成するために便利です。responseヘルパが引数なしで呼び出されると、Illuminate\Contracts\Routing\ResponseFactory契約が返されます。この契約はレスポンスを生成するための、様々なメソッドを提供しています。The response helper may be used to conveniently 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 status and headers, but also need to return a view[/docs/{{version}}/views] as the response content, you may use the view method:

return response()
            ->view('hello', $data)
            ->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 simply 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 into JSON using the json_encode PHP function:

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

JSONPレスポンスを生成したい場合は、jsonメソッドに追加してsetCallbackを使用してください。If you would like to create a JSONP response, you may use the json method in addition to setCallback:

return response()
            ->json(['name' => 'Abigail', 'state' => 'CA'])
            ->setCallback($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);

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

FileレスポンスFile Responses

fileメソッドは、ダウンロードの代わりに、ブラウザへ画像やPDFのようなファイルを表示するために使用します。このメソッドは第1引数にファイルパス、第2引数にヘッダの配列を指定します。The file method can 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);

リダイレクト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 method:

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

例えば送信されたフォーム内容にエラーがある場合など、直前のページヘユーザーをリダイレクトさせたい場合もあります。グローバルなbackヘルパ関数を使ってください。ただし、back関数を使用するルートはwebミドルウェアグループに属しているか、セッションミドルウェアが適用されることを確認してください。Sometimes you may wish to redirect the user to their previous location, for example, after a form submission that is invalid. You may do so by using the global back helper function. However, make sure the route using 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モデルの"ID"をルートパラメーターとしてリダイレクトする場合は、モデルをそのまま渡してください。IDは自動的にとり出されます。If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may simply pass the model itself. The ID will be extracted automatically:

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

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

コントローラーアクションに対するリダイレクトを生成することもできます。そのためには、コントローラーとアクションの名前をactionメソッドに渡してください。LaravelのRouteServiceProviderにより、デフォルトのコントローラー名前空間が自動的に設定されるため、コントローラーの完全名前空間名を指定する必要がないことを覚えておいてください。You may also generate redirects to controller actions[/docs/{{version}}/controllers]. To do so, simply 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 default controller namespace:

return redirect()->action('HomeController@index');

もちろん、コントローラールートにパラメーターが必要ならば、actionメソッドの第2引数として渡してください。Of course, 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 With Flashed Session Data

新しいURLへリダイレクトし、セッションへフラッシュデータを保存するのは、一度にまとめて行われる典型的な作業です。そのため便利なように、RedirectResponseを生成し、同時に一つのメッソッドをチェーンするだけでセッションへフラッシュデータを保存できます。これは特にアクションの後の状況を説明するメッセージを保存する場合に便利です。Redirecting to a new URL and flashing data to the session[/docs/{{version}}/session#flash-data] are typically done at the same time. So, for convenience, you may create a RedirectResponse instance and flash data to the session in a single method chain. This is particularly convenient for storing status messages after an action:

Route::post('user/profile', function () {
    // ユーザプロフィールの更新処理…

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

もちろん、ユーザを新しいページヘリダイレクトした後、セッションへ保存したフラッシュデータのメッセージを取り出し、表示する必要があります。たとえばBlade記法を使ってみましょう。Of course, after the user is redirected to a new page, you may retrieve and 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

レスポンスマクロResponse Macros

いろいろなルートやコントローラーで、再利用するためのカスタムレスポンスを定義したい場合はResponseファサード、もしくはIlluminate\Contracts\Routing\ResponseFactoryの実装に対し、macroメソッドが使用できます。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 or the implementation of Illuminate\Contracts\Routing\ResponseFactory.

たとえば、サービスプロバイダbootメソッドで定義します。For example, from a service provider's[/docs/{{version}}/providers] boot method:

<?php

namespace App\Providers;

use Response;
use Illuminate\Support\ServiceProvider;

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

ヘッダー項目移動

キーボード操作