booni3
2 months ago
436
15
Laravel

Form requests $this->user() vs. auth()->user() in authorization

Posted 2 months ago by booni3

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());
}

Please sign in or create an account to participate in this conversation.