总览

  1. // Using the global helper to generate a redirect response
  2. Route::get('redirect-with-helper', function () {
  3. return redirect()->to('login');
  4. });
  5. // Using the global helper shortcut
  6. Route::get('redirect-with-helper-shortcut', function () {
  7. return redirect('login');
  8. });
  9. // Using the facade to generate a redirect response
  10. Route::get('redirect-with-facade', function () {
  11. return Redirect::to('login');
  12. });
  13. // Using the Route::redirect shortcut in Laravel 5.5+
  14. 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() ==> https
  • action() ==> 跳转到控制器的方法 eg: redirect()->action('MyController@myMethod') or redirect()->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);
});