Using HTTP Status Codes with Laravel API Resources

Ali

May 24, 2020

When you are building an API, you can use Laravel API Resources to easily transform your models and model collections into JSON

This feature gives response with 200 OK by default. If you want to change the HTTP status code, you can try it this way:

return (new ExampleResource($example))->response()->setStatusCode(201);

Another way is overriding some methods on JsonResource class. Sometime we need to have a customize response, for example somthing like this:

{
    "errors": {
        "unauthorized": [
            "The username or password is incorrect"
        ]
    }
}

First create a new resource:

php artisan make:resource ErrorResource

Now you need to override your resource response:

public function toResponse($request)
{
    return (new ResourceResponse($this))->toResponse($request)->setStatusCode(401);
}

If you want to change status code dynamically you need to do a little more:

class ErrorResource extends JsonResource
{
    public $statusCode;
    public function __construct($resource, $statusCode = 401)
    {
        parent::__construct($resource);
        $this->statusCode = $statusCode;
    }
    public function toResponse($request)
    {
        return (new ResourceResponse($this))->toResponse($request)->setStatusCode($this->statusCode);
    }
}

And if you want to rename “data” to a customize key such as “errors” or “message” Just override $wrap property like this:

public static $wrap = 'errors';

Finally use that:

$errors = ['unauthorized' => 'The username or password is incorrect'];
return (new ErrorResource($errors , 422));