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

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners