我不确定这是"正确的"做事方式,但逻辑是有效的.我在Laravel设置中拥有自己的课程,我use在控制器中.在我的控制器中,我在自定义类中调用一个函数,但是如果在该函数中发生某些事情,我想重定向用户.
在IRC上聊天后,我告诉你不能在你自己的课程中进行重定向,你必须" 从控制器返回重定向响应对象".
不完全确定这意味着什么,但我想你必须从控制器那里做重定向.
代码(简化,它正在工作):
Controller method:
// Validate the incoming user
$v = new SteamValidation( $steam64Id );
// Check whether they're the first user
$v->checkFirstTimeUser();
Run Code Online (Sandbox Code Playgroud)
这将转到我的SteamValidation类(app/Acme/Steam/SteamValidation.php和namespaced),它会检查:
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;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果计数超过0,那么它只会返回控制器,我很乐意继续.但是,如果它是一个新用户并且我尝试进行重定向(return \Redirect::route('settings');),我会得到一个空白页面!
所以我的问题是:
您无法从嵌套方法重定向的原因是,简单地调用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');
}
Run Code Online (Sandbox Code Playgroud)
但是,虽然我们负责重定向您的验证方法,但您还应该负责创建用户:
// 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');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2093 次 |
| 最近记录: |