2015-10-19 81 views
2

我想将默认的Laravel路线从/auth/login更改为只有/登录和与注册表相对。Laravel 5.1 - 如何在AuthController中设置loginPath?

这是我的路线:

Route::get('login',  ['as' => 'getLogin', 'uses' => 'Auth\[email protected]']); 
Route::post('login', ['as' => 'postLogin', 'uses' => 'Auth\[email protected]']); 
Route::get('logout', ['as' => 'getLogout', 'uses' => 'Auth\[email protected]']); 
Route::get('register', ['as' => 'getRegister', 'uses' => 'Auth\[email protected]']); 
Route::post('register', ['as' => 'postRegister', 'uses' => 'Auth\[email protected]']); 

现在问题出现了,当用户试图访问被把守的区域,在认证类踢,重定向的未认证用户回/auth/login而不仅仅是/login

不过,我觉得我可以在我的AuthController设置$ LOGINPATH这样解决问题:

protected $loginPath = '/login'; 

但它似乎像$ LOGINPATH只是用于登录尝试失败,而不是不成功的身份验证尝试,如AuthenticateUsers类中所述。

嗯,我设法从这个在身份验证类改变的redirectUrl:

return redirect()->guest('auth/login'); 

这样:

return redirect()->guest('login'); 

这解决了问题,但我想设置一个属性在我的AuthController是这样的:

protected $redirectIfMiddlewareBlocks = '/login'; 

为此,我在身份验证类检查,如果属性存在,这是我在AuthController之前设置:

return redirect()->guest(property_exists($this, 'redirectIfMiddlewareBlocks') ? $this->redirectIfMiddlewareBlocks : '/shouldnotbeused'); 

但我得到/shouldnotbeused网址,而不是一个由redirectIfMiddlewareBlocks设置属性在我的AuthController中。

如何在我的AuthController中正确设置登录路径的路径?

+1

如果存在的话为什么要检查?你知道它存在,因为你刚刚添加它 – andrewtweber

+1

据我所知,这些是你需要设置登录路径的唯一两个地方。但我不明白为什么你要设置属性并检查它是否存在,从而使事情变得过于复杂。我只想用'redirect() - > guest('login')'' – andrewtweber

+0

的作品。嗯,我只是有点重构,并认为这将是一个好主意,将此路径保存在变量中的某个变量最佳。我检查它是否存在,看看它是否发现它,它不是 – LoveAndHappiness

回答

2

我认为问题在于你正在检查错误的类的属性。要检查,如果它存在于$this,这是实例身份验证,当它被设置在AuthController

所以,你应该改变你的检查:

property_exists(AuthController::class, 'redirectIfMiddlewareBlocks') 

而且,你不能从另一个类访问受保护的属性。如果你想这样做,你必须公开。最后,我会将其设置为静态的,以便您不必实例化AuthController对象来访问它。所以,最终的解决方案是:

class AuthController { 
    public static $redirectIfMiddlewareBlocks = '/here'; 
} 

并在您的身份验证的中间件:

use App\Http\Controllers\AuthController; 

class Authenticate { 
    public function handle() 
    { 
     return redirect()->guest(property_exists(AuthController::class, 'redirectIfMiddlewareBlocks') ? AuthController::redirectIfMiddlewareBlocks : '/shouldnotbeused'); 
    } 
} 
+0

非常感谢你安德鲁。 – LoveAndHappiness

+1

@LoveAndHappiness欢迎您。对不起,我起初误解了。我所做的**你所做的事情是无稽之谈,但实际上你在做什么,我认为如你所说,将所有重定向路径保留在一个地方是一个好主意 – andrewtweber

+0

还有一个问题。与您的解决方案,我得到:使用未定义的常量AuthController - 假设'AuthController' – LoveAndHappiness