Php Laravel 5.1-如何在AuthController中设置登录路径?
我想将默认的Laravel路由从/auth/login更改为仅/login,并与register相对 以下是我的路线:Php Laravel 5.1-如何在AuthController中设置登录路径?,php,laravel,authentication,laravel-5,Php,Laravel,Authentication,Laravel 5,我想将默认的Laravel路由从/auth/login更改为仅/login,并与register相对 以下是我的路线: Route::get('login', ['as' => 'getLogin', 'uses' => 'Auth\AuthController@getLogin']); Route::post('login', ['as' => 'postLogin', 'uses' => 'Auth\AuthController@postLogin'])
Route::get('login', ['as' => 'getLogin', 'uses' => 'Auth\AuthController@getLogin']);
Route::post('login', ['as' => 'postLogin', 'uses' => 'Auth\AuthController@postLogin']);
Route::get('logout', ['as' => 'getLogout', 'uses' => 'Auth\AuthController@getLogout']);
Route::get('register', ['as' => 'getRegister', 'uses' => 'Auth\AuthController@getRegister']);
Route::post('register', ['as' => 'postRegister', 'uses' => 'Auth\AuthController@postRegister']);
现在问题出现了,当用户试图访问受保护的区域时,身份验证类启动,将未经身份验证的用户重定向回/auth/login,而不仅仅是/login
我想我可以通过在我的AuthController中设置$loginPath来解决这个问题,如下所示:
protected $loginPath = '/login';
protected $redirectIfMiddlewareBlocks = '/login';
但是,$loginPath似乎只是用于不成功的登录尝试,而不是不成功的身份验证尝试,如AuthenticateUsers类中所述
我成功地更改了身份验证类中的重定向URL,如下所示:
return redirect()->guest('auth/login');
为此:
return redirect()->guest('login');
这解决了问题,但我想在我的AuthController中为此设置一个属性,如下所示:
protected $loginPath = '/login';
protected $redirectIfMiddlewareBlocks = '/login';
为此,我检查Authenticate类中是否存在属性,这是我在AuthController中设置的:
return redirect()->guest(property_exists($this, 'redirectIfMiddlewareBlocks') ? $this->redirectIfMiddlewareBlocks : '/shouldnotbeused');
然而,我得到的是/不应使用url,而不是AuthController中的redirectIfMiddlewareBlocks属性设置的url
如何在AuthController中正确设置登录路由的路径?我认为问题在于您检查了错误类的属性。您正在检查它是否存在于
$this
,当它设置为AuthController时,它是Authenticate的一个实例
因此,您应该将支票更改为:
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');
}
}
你为什么要检查它是否存在?你知道它的存在,因为你刚刚添加了它。据我所知,这是你需要设置登录路径的唯一两个地方。但是我不明白为什么设置属性并检查它是否存在会使事情变得过于复杂。我只想使用有效的
redirect()->guest('login')
嗯,我只是进行了一点重构,并认为将此路径保存在顶部某个变量中是个好主意。我检查它是否存在,看它是否找到了,但它没有,为什么要检查?属性是否永远不存在?以查看它是否实际接受在authcontroller中设置的权限。但事实并非如此。我也理解你问题的含义。你是说如果你先设置属性,为什么还要费心检查属性是否存在。我读了一些traits,得到了一个想法,给类的用户一个选项set一个属性,这与默认的属性不同,然后可能根本不设置它。但选择应该存在。希望你能理解……非常感谢安德鲁。@loveandhappy不客气。对不起,一开始我误解了。我认为你所做的是荒谬的,但你实际上所做的,我认为是一个好主意,正如你所说的,将所有重定向路径保持在一个位置。还有一个问题。有了你的解决方案,我得到了:使用未定义的常量AuthController-假定为'AuthController'@LoveAndHappiness啊,是的,检查我的更新property\u exists
需要类名,所以我将其更改为AuthController::class