我不确定这是“正确”的做事方式,但逻辑是可行的。我在我的 Laravel 设置中有自己的类,我在 Controller 中使用
。在我的 Controller 中,我在我的自定义类中调用了一个函数,但是如果该函数中发生某些事情,我想重定向用户。
在 IRC 上聊天后,我被告知你不能在你自己的类中进行重定向,你必须“从 Controller 返回重定向响应对象”。
不完全确定这是什么意思,但我猜你必须改为从 Controller 进行重定向。
代码(经过简化,可以正常工作):
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,它就会返回到 Controller ,我很乐意继续。但是,如果它是新用户并且我尝试进行重定向(return\Redirect::route('settings');
),我会得到一个空白页面!
所以我的问题是:
- 为什么我无法从这里重定向?
- 将响应返回给 Controller 然后进行重定向的正确方法是什么?
最佳答案
无法从嵌套方法重定向的原因是简单地调用 Redirect::route() 不会触发重定向。您的 Controller 的方法将返回一些 Laravel 然后查看以决定要做什么 - 如果它是一个 View 它将显示它,如果它是一个 Redirect 它将进行重定向。在您的嵌套方法中,您可以返回您想要的内容,但只要在 Controller 中它没有将其传递给下线,那么它对您就没有好处。
此外,您可能无论如何都不应该在辅助函数中返回重定向。如果您的验证函数有一个 bool 值响应(是的,一切都很好,没有什么不好的),那么您可以简单地返回 true/false,然后在 Controller 中选择它来进行重定向:
// 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');
}
关于php - Laravel:在自定义类中重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21752920/