【问题标题】:How to redirect to a route in a called function laravel如何重定向到被调用函数laravel中的路由
【发布时间】:2013-10-22 17:55:17
【问题描述】:

我正在整理我的代码,删除表单处理程序函数之外的登录函数对我来说是有意义的。但是,当我在被调用函数中调用返回路由行时,它只是将此路由返回给父控制器,父控制器对此不做任何事情。我希望我的重定向在被调用的函数中执行。

public static function loginFormHandler(){

 //some stuff is done

$this->doLogin();
}

public static function doLogin(){

if (\Auth::attempt($this->credentials, $this->remember)) {
         return \Redirect::route("dashboard");
    }

}

它不是重定向而是返回到 loginFormHandler ,我知道这是因为它不会进入仪表板页面。

【问题讨论】:

  • 问题似乎不是重定向到路由,而是身份验证。您可以将代码粘贴到您验证用户是否已登录并重定向到 loginFormHandler 的位置吗?

标签: php laravel laravel-4


【解决方案1】:

这是不可能的。当您说return Redirect::route('dashboard') 时,它将该函数调用返回给调用函数,而不是执行该函数。通过离开返回,它仍然返回到调用函数。

我已经重新组织了我的逻辑。

【讨论】:

    【解决方案2】:

    您必须返回从方法调用返回的内容。第一个函数应该是这样的:

    public static function loginFormHandler(){
    
        //some stuff is done
    
        return $this->doLogin();
    }
    

    【讨论】:

      【解决方案3】:

      但是,您可以重定向到 URL:

      Redirect::to('/dashboard');
      

      那是一条路线:

      Route::get('/dashboard', 'DashboardController@index');
      

      祝你好运

      【讨论】:

      • 它仍然会出错,因为它返回到被调用的函数,而不是简单地转到仪表板页面。我知道这一点,因为它已进入布局视图并期待一个变量。没有变量,因为loginformhandler 没有传递任何变量。
      【解决方案4】:

      我喜欢将重定向固定在控制器上,以便在需要时更改 SEO 策略。实现这一点非常简单:

      return Redirect::action('SomeController@someFunction');
      

      希望对你有帮助

      【讨论】:

        【解决方案5】:

        您好,我现在正在构建一个 Lumen API,我需要相同的功能来从其他函数返回响应。

        我希望这会有所帮助。

        //helpers.php
        function responseWithJsonErrorsArray($text, $code)
            return response('error' => $text, $code);
        
        //FooTrait.php
        protected function fooBar(){
           responseWithJsonError('Foo Error', 404)->send();
           exit;
        }
        

        【讨论】:

          【解决方案6】:

          您可以简单地返回函数中返回的内容,例如:

          public static function loginFormHandler(){
          
              //some stuff is done
          
              return $this->doLogin();
          }
          
           public static function doLogin(){
          
           if (\Auth::attempt($this->credentials, $this->remember)) {
               return \Redirect::route("dashboard");
           }
          

          }

          【讨论】:

            【解决方案7】:

            查看docs

            你可以使用:

            return redirect('home/dashboard');
            return redirect()->route('profile', ['id' => 1]);
            return redirect()->action('HomeController@index');
            return redirect('dashboard')->with('status', 'Profile updated!');
            ...
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2014-05-04
              • 2014-02-06
              • 2021-07-22
              • 2017-06-19
              • 2021-04-26
              • 2020-03-24
              • 2019-05-13
              相关资源
              最近更新 更多