Skip to content
全部文档

HTTP 重定向

创建重定向

重定向响应是 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]);

通过 Eloquent 模型填充参数

若你重定向到带有从 Eloquent 模型填充的「ID」参数的路由,可以直接传入该模型。ID 会自动提取:

// For a route with the following URI: profile/{id}

return redirect()->route('profile', [$user]);

若希望自定义放入路由参数的值,应覆盖 Eloquent 模型上的 getRouteKey 方法:

php
/**
 * 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();

用户被重定向后,你可以从 会话 显示闪存消息。例如,使用 Blade 语法

@if (session('status'))
    <div class="alert alert-success">
        &#123;&#123; session('status') &#125;&#125;
    </div>
@endif