Laravel 响应:重定向到路由
问题
在控制器或路由中,该怎样重定向至命名路由?
回答
为路由指定了名称后,要在控制器或路由中重定向到该路由,有多种方式:
方式一:通过 redirect
全局辅助函数
当以不带参数形式调用全局辅助函数 redirect
时,它会返回 Illuminate\Routing\Redirector
实例。这个实例允许你调用 Redirector
上的任何方法。要生成命名路由的重定向响应,可链式调用 Redirector
上的 route
方法:
return redirect()->route('profile');
如果路由中有参数,可以将其作为第二个参数传递到 route
方法:
// 对于具有以下 URI 的路由: profile/{id}
return redirect()->route('profile', ['id' => 1]);
方式二:通过 Redirect::route
方法
我们也可直接调用 Redirect
门面的 route
方法。
return Redirect::route('profile');
带路由参数:
return Redirect::route('profile', ['id' => 1]);
推荐文章: