[英]Laravel form request - $this->user() vs. auth()->user() in authorization
Can anyone explain if there is a reason why we should not be using getting the authenticated user within a from request authorize
method, via the Auth::user()
or auth()->user()
helpers vs. the $this->user()
method as suggested in docs? 任何人都可以通过Auth::user()
或auth()->user()
助手与$this->user()
说明是否有理由为什么我们不应该使用从请求authorize
方法中获取经过身份验证的用户docs中建议的$this->user()
方法?
https://laravel.com/docs/5.8/validation#authorizing-form-requests https://laravel.com/docs/5.8/validation#authorizing-form-requests
In my case, I am trying to unit test a form request and auth()->user()
allows me to retrieve the user whereas $this->user()
does not as I am not making a full request. 就我而言,我正在尝试对表单请求进行单元测试,而auth()->user()
允许我检索用户,而$this->user()
却没有,因为我没有提出完整的请求。 I am just creating the form request object for my test. 我只是为测试创建表单请求对象。
public function setUp(): void
{
parent::setUp();
$this->subject = new \App\Http\Requests\OrderStoreRequest();
}
// Acting as has no effect when manually creating the orderStoreRequest object
public function testAuthorize()
{
$this
->actingAs(\factory(User::class)->create())
->assertTrue($this->subject->authorize());
}
ActingAs()
is calling the Laravel Auth system, which in the request lifecycle is put into the request ( See ). ActingAs()
正在调用Laravel Auth系统,该系统在请求生命周期中被放入请求中( 请参阅参考资料 )。 Since you are just calling your request without this lifecycle, you will never get anything injected into the Request. 由于您只是在没有此生命周期的情况下调用请求,因此您将永远不会注入任何请求。
For your code to work, you need to set the UserResolver. 为了使代码正常工作,您需要设置UserResolver。 This can be done like so. 可以这样做。
$this->subject->setUserResolver(function () use($user) {
return $user;
});
For ease of usage, i would highly recommend doing Laravel feature tests instead of unit testing. 为了易于使用,我强烈建议您进行Laravel功能测试,而不要进行单元测试。 You are gonna fight your way through a lot of approaches, there is not meant to be called without the Laravel lifecycle. 您将通过许多方法来斗争,没有Laravel生命周期就不会被称为。 Which you will get doing call() and json() on the app. 您将在应用程序上执行call()和json()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.