Laravel - 重定向到控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20028354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:39:53  来源:igfitidea点击:

Laravel - redirect to controller

phpcontrollerlaravel

提问by devs

I keep getting: Unknown action [HomeController@showHome]

我不断得到: Unknown action [HomeController@showHome]

Route:

路线:

Route::get('/', ['before' => 'checkUserFilter'], 'HomeController@showHome');
Route::get('/createUser', 'UserController@createUser');

Filter:

筛选:

Route::filter('checkUserFilter', function() 
{
    if (Auth::guest()) 
    {
        return Redirect::action('UserController@createUser');
    }  

});

Controller:

控制器:

userController

用户控制器

public function createUser()
{
   // removed everything else, the return redirect action isn't working.

  return Redirect::action('HomeController@showHome');
}

homeController

家庭控制器

public function showHome()
{
    return View::make('home');
}

When a user loads the webpage, the filter checks if he's a guest or not, if he is, go to the createUser method in UserController.php. It creates the user, but it doesn't redirect back to HomeController. How can I stop the above error so it redirect back to the HomeController?

当用户加载网页时,过滤器会检查他是否是访客,如果是,则转到 UserController.php 中的 createUser 方法。它会创建用户,但不会重定向回 HomeController。如何停止上述错误,使其重定向回 HomeController?

I also have another question: What would be a better way to place the return redirection action, besides in the method? I would like it if I can use this same method for multiple things, for example create a user in the admin control panel.

我还有另一个问题:除了在方法中之外,还有什么更好的方式来放置返回重定向操作?如果我可以将相同的方法用于多种用途,例如在管理控制面板中创建用户,我会很高兴。

回答by Henry Cho

I assume your route to HomeController is where the problem exists.

我假设您到 HomeController 的路线是问题所在。

Here are two possible solutions:

这里有两种可能的解决方案:

Solution 1: routes.php

解决方案1:routes.php

Route::get('/', array('before'=>'checkUserFilter', 'uses'=>'HomeController@showHome'));

Solution 2: HomeController.php

解决方案2:HomeController.php

public function __construct(){
    $this->beforeFilter('checkUserFilter');
}

//showHome

Haven't tested it, but hope that helps.

没有测试过,但希望有帮助。