总览
// Using the global helper to generate a redirect responseRoute::get('redirect-with-helper', function () {return redirect()->to('login');});// Using the global helper shortcutRoute::get('redirect-with-helper-shortcut', function () {return redirect('login');});// Using the facade to generate a redirect responseRoute::get('redirect-with-facade', function () {return Redirect::to('login');});// Using the Route::redirect shortcut in Laravel 5.5+Route::redirect('redirect-by-route', 'login');
rdirect()->to()
/**
* @param null $to 路径
* @param int $status html 状态码
* @param array $headers html 请求头
* @param null $secure http or htps
*/
function to($to = null, $status = 302, $headers = [], $secure = null){}
redirect()->route()
/**
* @param null $to 路由名
* @param array $parameters 参数
* @param int $status 状态码
* @param array $headers html 头
*/
function route($to = null, $parameters = [], $status = 302, $headers = []){}
其余路由
back()==> 返回之前的路由home()==> 跳转到名字叫 home 的路由refresh()==> 刷新away()==> 跳转到外部路由secure()==> httpsaction()==> 跳转到控制器的方法 eg:redirect()->action('MyController@myMethod')orredirect()->action([MyController::class, 'myMethod'])guest()==> 用于认证系统内部使用,未登录的用户登录时,将会捕获并重定向 (不太懂)intended()==> 用于认证系统内部,身份验证成功后获取 guest() 方法存储的预期url,并重定向
redirect()->with()
with() 用于传递参数,支持链式调用。
Route::get('redirect-with-key-value', function () {
return redirect('dashboard')
->with('error', true);
});
Route::get('redirect-with-array', function () {
return redirect('dashboard')
->with(['error' => true, 'message' => 'Whoops!']);
});
withInput() 传递表单的值
Route::get('form', function () {
return view('form');
});
Route::post('form', function () {
return redirect('form')
->withInput()
->with(['error' => true, 'message' => 'Whoops!']);
});
old() 获取 flash 的变量
<input name="username" value="<?=old('username', 'Default username instructions here');?>">
withErrors() 传递错误信息
Route::post('form', function (Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), $this->validationRules);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
});
请求终止
Route::post('something-you-cant-do', function (Illuminate\Http\Request $request) {
abort(403, 'You cannot do that!');
abort_unless($request->has('magicToken'), 403);
abort_if($request->user()->isBanned, 403);
});
