Source: juststeveking.uk

Laravel Response Classes
Responding from your Laravel application is what I would call vital, especially when you are building an API. Many of us typically start with using the helper functions in our applications, as the docs and many tutorials will use them.

Let’s see what that might look like: return new JsonResponse( data: [], status: JsonResponse::HTTP_OK, ); The JsonResponse class extends the Symfony Response class through a few layers of abstraction so that you can call this directly - however, your static analyzer may complain about this.

class CollectionResponse implements Responsable { public function __construct( public readonly JsonResourceCollection $data, public readonly Http $status = Http::OK, ) {} public function toResponse($request): Response { return new JsonResponse( data: $this->data, status: $this->status->value, ); }}

trait SendsResponse { public function toResponse($request): Response { return new JsonResponse( data: $this->data, status: $this->status->value, ); }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners