jsphpl's avatar

Why does Laravel respond with a 201 status code by default?

Can anyone explain why the status code of the response generated by Laravel would be 201 instead of 200?

<?php

namespace App\Http\Actions\User;

use App\Http\Resources\UserResource;
use Illuminate\Support\Facades\Auth;

class ShowMeAction
{
    public function __invoke()
    {
        return new UserResource(Auth::user());
    }
}

Middleware for this action is the default "api" middleware stack coming with Laravel 5.7 + spatie/cors + auth:api.

Other actions correctly return a 200 status code without me specifying anything…

Here's the failing test:

$response = $this->actingAs($user, 'api')->get('/api/v1/users/me');
$response->assertOk();
1) Tests\Feature\User\ShowMeTest::test_it_shows_the_authenticated_users_resource
Response status code [201] does not match expected 200 status code.
Failed asserting that false is true.
0 likes
5 replies
tykus's avatar
tykus
Best Answer
Level 104

This is because the User instance wasRecentlyCreated - I assume you used a factory to create the user prior to the test request - and 201 is the appropriate response status code in that circumstance.

https://github.com/laravel/framework/pull/21625/files

I feel that this is too opinionated. Clearly in the context of your test, this behaviour is not correct.

1 like
jsphpl's avatar

Thanks @tykus! That's what i feared – a case of Laravel trying to be too smart… Think i'm going to file an issue about this.

jsphpl's avatar

As by this issue, the workaround is to call fresh() on the user before passing it to actingAs().

Please or to participate in this conversation.