レスポンスの生成Creating Responses
文字列と配列Strings and 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];
});
Eloquentコレクションも返せることを知っていますか? 自動的にJSONへ変換されます。試してください![!NOTE]
Note:
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 and 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 and Encryption
デフォルトではありがたいことに、Illuminate\Cookie\Middleware\EncryptCookies
ミドルウェアのおかげで、Laravelが生成したすべてのクッキーは暗号化され、クライアントによって変更されたり読み取られたりしないように署名を付けます。アプリケーションが生成したクッキーのサブセットの暗号化を無効にしたい場合は、アプリケーションのbootstrap/app.php
ファイルで、encryptCookies
メソッドを使用してください。By default, thanks to the
Illuminate\Cookie\Middleware\EncryptCookies
middleware, 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
encryptCookies
method in your
application's bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) {
$middleware->encryptCookies(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:
/**
* モデルのルートキー値の取得
*/
public function getRouteKey()Update the user...: mixed
{
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);
[!WARNING]
Warning! ファイルダウンロードを管理しているSymfony HttpFoundationクラスは、ASCIIのダウンロードファイル名を指定するよう要求しています。
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 absolute 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
{
/**
* 全アプリケーションサービスの初期起動処理
*/
public function boot(): void
{
Response::macro('caps', function (string $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');