重定向响应是 Illuminate/Http/RedirectResponse 类的实例,并包含将用户重定向到另一个 URL 所需的正确标头。有几种方法可以生成 RedirectResponse 实例。最简单的方法是使用全局 redirect 辅助函数:
Route::get('/dashboard', function () {
return redirect('/home/dashboard');
});有时您可能希望将用户重定向到他们之前的位置,例如当提交的表单无效时。您可以使用全局 back 辅助函数来实现此目的。由于此功能利用了 会话,请确保调用 back 函数的路由正在使用 web 中间件组或已应用所有会话中间件:
Route::post('/user/profile', function () {
// Validate the request...
return back()->withInput();
});当你调用不带任何参数的 redirect 辅助函数时,会返回一个 Illuminate\Routing\Redirector 的实例,让你能够在该 Redirector 实例上调用任何方法。例如,要生成一个指向命名路由的 RedirectResponse,你可以使用 route 方法:
return redirect()->route('login');如果你的路由有参数,你可以将它们作为第二个参数传递给 route 方法:
// For a route with the following URI: profile/{id}
return redirect()->route('profile', ['id' => 1]);为方便起见,Laravel 也提供了全局的 to_route 函数:
return to_route('profile', ['id' => 1]);如果你正在重定向到一个带有“ID”参数的路由,并且该参数正在从一个 Eloquent 模型填充,你可以传递模型本身。该 ID 将会自动提取:
// For a route with the following URI: profile/{id}
return redirect()->route('profile', [$user]);如果你想要自定义放置在路由参数中的值,你应该覆盖你的 Eloquent 模型上的 getRouteKey 方法:
/**
* Get the value of the model's route key.
*/
public function getRouteKey(): mixed
{
return $this->slug;
}您也可以生成重定向到 控制器动作。为此,将控制器和动作名称传递给 action 方法:
use App\Http\Controllers\HomeController;
return redirect()->action([HomeController::class, 'index']);如果你的控制器路由需要参数,你可以将它们作为第二个参数传递给 action 方法:
return redirect()->action(
[UserController::class, 'profile'], ['id' => 1]
);重定向到一个新的URL和将数据闪存到会话通常是同时进行的。通常,这会在成功执行某个操作后完成,届时你会将一条成功消息闪存到会话中。为方便起见,你可以在一个单一的、流畅的方法链中创建一个RedirectResponse实例并将数据闪存到会话:
Route::post('/user/profile', function () {
// Update the user's profile...
return redirect('/dashboard')->with('status', 'Profile updated!');
});您可以使用 RedirectResponse 实例提供的 withInput 方法,在将用户重定向到新位置之前,将当前请求的输入数据闪存到会话中。一旦输入数据被闪存到会话中,您就可以在下一次请求中轻松地检索它:
return back()->withInput();用户重定向后,你可以显示闪存消息来自session. 例如,使用Blade syntax:
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif