リダイレクトの作成Creating 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}ルートへのリダイレクト
return redirect()->route('profile', ['id' => 1]);
使い勝手を良くするため, Laravelはto_routeグローバル関数も提供しています。For convenience, Laravel also offers the global to_route function:
return to_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}ルートへのリダイレクト
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:
/**
* モデルのルートキー値の取得
*/
public function getRouteKey(): 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\HomeController;
return redirect()->action([HomeController::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 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!');
});
ユーザーを新しい場所にリダイレクトする前に、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. Once the input has been flashed to the session, you may easily retrieve it[/docs/{{version}}/requests#retrieving-old-input] during the next request:
return back()->withInput();
ユーザーをリダイレクトしたあと、セッションの一時保持データとして保存したメッセージを表示できます。例として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