简体   繁体   中英

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?

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. 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 ). 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. 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. You are gonna fight your way through a lot of approaches, there is not meant to be called without the Laravel lifecycle. Which you will get doing call() and json() on the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM