【问题标题】:How to perform an "internal" redirect in Laravel 5.3如何在 Laravel 5.3 中执行“内部”重定向
【发布时间】:2016-12-17 05:49:17
【问题描述】:

我了解如何使用 redirect() 方法重定向用户,但此方法返回 302 代码并且浏览器必须发出第二个 HTTP 请求。是否可以在内部将请求转发到不同的控制器和操作?

我正在中间件中进行此检查,因此我的句柄函数如下所示:

public function handle($request, Closure $next)
  {
    if (auth()->user->age <= 20) { //example
        //internally forward the user to a different controller@action
    }

    return $next($request);
  }

}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    您可以将call 方法用作:

    app()->call('App\Http\Controllers\ControllerName@funName')
    

    或者

    app('App\Http\Controllers\ControllerName')->funName();
    

    所以你的中间件看起来像:

    if (auth()->user->age <= 20) {
       return app()->call('App\Http\Controllers\ControllerName@action');
    }
    

    【讨论】:

    • 当我这样做时,我收到错误“调用 null 上的成员函数 setCookie()”。在 VerifyCsrfToken.php 第 136 行 FatalErrorException->__construct('message' => '???', 'code' => '???', 'severity' => '???', 'filename' => '???', 'lineno' => '???', 'traceOffset' => '???', 'traceArgs' => '???', 'trace' => '???')在 HandleExceptions.php 第 133 行的 HandleExceptions->fatalExceptionFromError('error' => '???', 'traceOffset' => '???') 在 HandleExceptions.php 第 118 行的 HandleExceptions->handleShutdown() 中。 php第0行
    【解决方案2】:

    您可以像这样使用redirect() 辅助方法:

    public function handle($request, Closure $next)
    {
      if (auth()->user->age <= 20) { //example
          return redirect()->route('some_route_name');
      }
    
      return $next($request);
    }
    

    在你的路由文件中,路由应该被定义为:

    Route::get('users/age/', 'ExampleController@method_name')->name('some_route_name');
    

    希望这会有所帮助!

    【讨论】:

    猜你喜欢
    • 2017-04-19
    • 2017-04-12
    • 1970-01-01
    • 2017-07-17
    • 2017-04-17
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多