レスポンスの基本Basic Responses
ルートからの文字列のリターンReturning Strings From Routes
Laravelのルートから返す、一番基本的なレスポンスは文字列です。The most basic response from a Laravel route is a string:
Route::get('/', function()
{
	return 'Hello World';
});
カスタムレスポンスの生成Creating Custom Responses
しかしながら、ほとんどのルートでは、コントローラーアクションから、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/master/views]. Returning a full Response instance allows you 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;
return (new Response($content, $status))
              ->header('Content-Type', $value);
responseヘルパも、便利に使用できます。For convenience, you may also use the response helper:
return response($content, $status)
              ->header('Content-Type', $value);
注目:
Responseメソッドの完全なリストは、APIドキュメントと、SymfonyのAPIドキュメントをご覧ください。Note: For a full list of availableResponsemethods, check out its API documentation[http://laravel.com/api/master/Illuminate/Http/Response.html] and the Symfony API documentation[http://api.symfony.com/2.5/Symfony/Component/HttpFoundation/Response.html].
レスポンスへのビュー送信Sending A View In A Response
Responseクラスメソッドにアクセスする必要があるが、レスポンスの内容としてビューを返したい場合は、viewメソッドが便利でしょう。If you need access to the Response class methods, but want to return a view as the response content, you may use the view method for convenience:
return response()->view('hello')->header('Content-Type', $type);
クッキー付きレスポンスAttaching Cookies To Responses
return response($content)->withCookie(cookie('name', 'value'));
メソッドチェーンMethod Chaining
ほとんどのResponseメソッドはチェーンできることを覚えておきましょう。レスポンスをスラスラ構築できます。Keep in mind that most Response methods are chainable, allowing for the fluent building of responses:
return response()->view('hello')->header('Content-Type', $type)
                 ->withCookie(cookie('name', 'value'));
リダイレクトRedirects
リダイレクトのレスポンスには、ほとんどの場合Illuminate\Http\RedirectResponseクラスのインスタンスを使用します。このクラスは、ユーザーを他のURLへリダイレクトさせるために必要な、しっかりとしたヘッダーが含まれています。Redirect responses are typically instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL.
リダイレクトのリターンReturning A Redirect
RedirectResponseインスタンスを生成する方法はたくさんあります。一番シンプルな方法は、redirectヘルパを使うことです。テストの時にリダイレクトレスポンスを生成するモックは一般的ではありませんから、ほとんどの場合、これで大丈夫でしょう。There are several ways to generate a RedirectResponse instance. The simplest method is to use the redirect helper method. When testing, it is not common to mock the creation of a redirect response, so using the helper method is almost always acceptable:
return redirect('user/login');
フラッシュデータ指定のリダイレクトReturning A Redirect With Flash Data
新しいURLへリダイレクトし、フラッシュデーターをセッションへ保存するのは、同時に行われるのが典型的です。ですから、利便性を上げるために、RedirectResponseインスタンスを生成し、同時に同じメソッドチェーンで、フラッシュデーターをセッションへ保存することもできます。Redirecting to a new URL and flashing data to the session[/docs/master/session] 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:
return redirect('user/login')->with('message', 'Login Failed');
直前のURLへのリダイレクトRedirecting To The Previous URL
直前のURLへユーザーをリダイレクトしたい場合があります。例えば、フォーム送信後です。backメソッドで行います。You may wish to redirect the user to their previous location, for example, after a form submission. You can do so by using the back method:
return redirect()->back();
return redirect()->back()->withInput();
名前付きルートへのリダイレクトReturning A Redirect To A Named Route
redirectヘルパを引数なしで呼び出すと、Illuminate\Routing\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');
引数指定の名前付きルートへのリダイレクトReturning A Redirect To A Named Route With Parameters
ルートに引数がある場合、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]);
あるルートへ"id"パラメータを伴い、Eloquentモデルを取得するルートへリダイレクトする場合、モデル自身をそのまま渡してください。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]);
名前付き引数指定の名前付きルートへのリダイレクトReturning A Redirect To A Named Route Using Named Parameters
//profile/{user}へのルート
return redirect()->route('profile', ['user' => 1]);
コントローラーアクションへのリダイレクトReturning A Redirect To A Controller Action
名前付きルートへのRedirectResponseインスタンスの生成と同様に、controller actionsへのリダイレクトも生成可能です。Similarly to generating RedirectResponse instances to named routes, you may also generate redirects to controller actions[/docs/master/controllers]:
return redirect()->action('App\Http\Controllers\HomeController@index');
注目:
URL::setRootControllerNamespaceにより、コントローラーのルート名前空間が登録されていれば、完全な名前空間を指定する必要はありません。Note: You do not need to specify the full namespace to the controller if you have registered a root controller namespace viaURL::setRootControllerNamespace.
引数指定コントローラーアクションへのリダイレクトReturning A Redirect To A Controller Action With Parameters
return redirect()->action('App\Http\Controllers\UserController@profile', [1]);
名前付き引数指定のコントローラーアクションへのリダイレクトReturning A Redirect To A Controller Action Using Named Parameters
return redirect()->action('App\Http\Controllers\UserController@profile', ['user' => 1]);
その他のレスポンスOther Responses
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/master/contracts] is returned. This contract provides several helpful methods for generating responses.
JSONレスポンスの生成Creating A JSON Response
jsonメソッドは、Content-Typeヘッダーに、application/jsonを自動的にセットします。The json method will automatically set the Content-Type header to application/json:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
JSONPレスポンスの生成Creating A JSONP Response
return response()->json(['name' => 'Abigail', 'state' => 'CA'])
                 ->setCallback($request->input('callback'));
ファイルダウンロードレスポンスの生成Creating A File Download Response
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.
レスポンスマクロ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/master/providers] boot method:
<?php namespace App\Providers;
use Response;
use Illuminate\Support\ServiceProvider;
class ResponseMacroServiceProvider extends ServiceProvider {
	/**
	 * 登録したサービスが起動後に実行
	 *
	 * @return void
	 */
	public function boot()
	{
		Response::('caps', function($value) use ($response)
		{
			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. The macro's Closure will be executed when calling the macro name from a ResponseFactory implementation or the response helper:
return response()->caps('foo');