【问题标题】:Laravel: Redirect within custom class?Laravel:在自定义类中重定向?
【发布时间】:2014-02-13 20:38:04
【问题描述】:

我不确定这是不是“正确”的做事方式,但逻辑是可行的。我在 Laravel 设置中有自己的课程,我在控制器中 use。在我的控制器中,我在自定义类中调用了一个函数,但是如果该函数中发生某些事情,我想重定向用户。

在 IRC 上聊天后,有人告诉我你不能在自己的类中进行重定向,你必须“从控制器返回重定向响应对象 ”。

不完全确定这意味着什么,但我想您必须改为从控制器执行重定向。

代码(已简化,正在运行):

Controller method:

    // Validate the incoming user
    $v = new SteamValidation( $steam64Id );

    // Check whether they're the first user
    $v->checkFirstTimeUser();

这会转到我的 SteamValidation 类(app/Acme/Steam/SteamValidation.php 和命名空间),它会进行检查:

public function checkFirstTimeUser() {

    // Is there any users?
    if( \User::count() == 0 ) {

        $user_data = [
           // Data
        ];

        // Create the new user
        $newUser = \User::create( $user_data );

        // Log that user in
        \Auth::login($newUser);

        // Redirect to specific page
        return \Redirect::route('settings');
    }

    return;
}

现在如果计数超过 0,那么它就会返回到控制器,我很乐意继续。但是,如果它是新用户并且我尝试进行重定向 (return \Redirect::route('settings');),我会得到一个空白页面!

所以我的问题是:

  • 为什么我无法从这里重定向?
  • 将响应返回给控制器,然后进行重定向的正确方法是什么?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您不能从嵌套方法重定向的原因是简单地调用 Redirect::route() 不会触发重定向。你的控制器的方法会返回一些 Laravel 的方法,然后看它来决定做什么——如果它是一个 View,它会显示它,如果它是一个 Redirect,它会做一个重定向。在您的嵌套方法中,您可以返回您想要的内容,但只要在控制器中它没有将其传递给您,那么它对您没有好处。

    此外,您可能也不应该在辅助函数中返回重定向。如果您的验证函数有一个布尔响应(是的,一切都很好,没有什么不好),那么您可以简单地返回 true/false,然后在控制器中选择它来进行重定向:

    // Validate the incoming user
    $v = new SteamValidation( $steam64Id );
    
    // Check whether they're the first user
    if ($v->isFirstTimeUser()) { // note I renamed this method, see below
        return \Redirect::route('settings');
    }
    

    但是,虽然我们负责从您的验证方法中重定向,但您也应该负责创建用户离开:

    // SteamValidation
    public function isFirstTimeUser() {
        return (\User::count() == 0);
    }
    
    // Controller
    
    // Validate the incoming user
    $v = new SteamValidation( $steam64Id );
    
    // Check whether they're the first user
    if ($v->isFirstTimeUser()) {
        // you may even wish to extract this user creation code out to something like a repository if you wanna go for it
    
        $user_data = [
           // Data
        ];
    
        // Create the new user
        $newUser = \User::create( $user_data );
    
        // Log that user in
        \Auth::login($newUser);
    
        // Redirect to specific page
        return \Redirect::route('settings');
    }
    

    【讨论】:

    • 非常感谢您的解释。我会查看存储库,尝试清理我的编码:)
    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 2021-01-11
    • 1970-01-01
    • 2018-04-14
    • 2018-04-30
    • 2015-05-28
    • 2016-01-16
    • 2021-01-12
    相关资源
    最近更新 更多