基本のレスポンス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.
しかし通常、ほとんどのルートとコントローラーアクションからは、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/2.7/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');
クッキーの付加Attaching Cookies To Responses
withCookie
ヘルパメソッドをレスポンスインスタンスに使えば、簡単にクッキーを付加できます。たとえば、withCookie
メソッドを使いクッキーを作成し、レスポンスインスタンスに付加できます。The withCookie
helper method on the response instance allows you to
easily attach cookies to the response. For example,
you may use the withCookie
method to
generate a cookie and attach it to the response
instance:
return response($content)->header('Content-Type', $type)
->withCookie('name', 'value');
withCookie
メソッドはクッキーのプロパティーをカスタマイズするためのオプション引数を受け付けます。The withCookie
method accepts additional optional arguments which
allow you to further customize your cookie's
properties:
->withCookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
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 may 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.
リダイレクト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
ヘルパ関数を使ってください。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:
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}のルート定義に対するリダイレクト
return redirect()->route('profile', [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', [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', 'プロファイル更新!');
});
もちろん、ユーザーを新しいページヘリダイレクトした後、セッションへ保存したフラッシュデータのメッセージを取り出し、表示する必要があります。たとえば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
いろいろなルートやコントローラーで、再利用するためのカスタムレスポンスを定義したい場合は、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 an implementation of
Illuminate\Contracts\Routing\ResponseFactory
.
たとえば、サービスプロバイダーのboot
メソッドで定義します。For example, from a service
provider's[/docs/{{version}}/providers]
boot
method:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\ResponseFactory;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* サービス初期処理登録後に実行
*
* @param ResponseFactory $factory
* @return void
*/
public function boot(ResponseFactory $factory)
{
$factory->macro('caps', function ($value) use ($factory) {
return $factory->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');