Skip to main content
Back to packages
644 GitHub stars

f9webltd/laravel-api-response-helpers

View on GitHub

Description

A simple package allowing for consistent API responses throughout your Laravel application.

Simply reference the required trait within your controller:

<?php
 
namespace App\Http\Api\Controllers;
 
use F9Web\ApiResponseHelpers;
use Illuminate\Http\JsonResponse;
 
class OrdersController
{
use ApiResponseHelpers;
 
public function index(): JsonResponse
{
return $this->respondWithSuccess();
}
}

Optionally, the trait could be imported within a base controller.

Available methods

respondNotFound(string|Exception $message, ?string $key = 'error')

Returns a 404 HTTP status code, an exception object can optionally be passed.

respondWithSuccess(array|Arrayable|JsonSerializable|null $contents = null)

Returns a 200 HTTP status code, optionally $contents to return as json can be passed. By default returns ['success' => true].

respondOk(string $message)

Returns a 200 HTTP status code

respondUnAuthenticated(?string $message = null)

Returns a 401 HTTP status code

respondForbidden(?string $message = null)

Returns a 403 HTTP status code

respondError(?string $message = null)

Returns a 400 HTTP status code

respondCreated(array|Arrayable|JsonSerializable|null $data = null)

Returns a 201 HTTP status code, with response optional data

respondNoContent(array|Arrayable|JsonSerializable|null $data = null)

Returns a 204 HTTP status code, with optional response data. Strictly speaking, the response body should be empty. However, functionality to optionally return data was added to handle legacy projects. Within your own projects, you can simply call the method, omitting parameters, to generate a correct 204 response i.e. return $this->respondNoContent()

setDefaultSuccessResponse(?array $content = null): self

Optionally, replace the default ['success' => true] response returned by respondWithSuccess with $content. This method can be called from the constructor (to change default for all calls), a base API controller or place when required.

setDefaultSuccessResponse is a fluent method returning $this allows for chained methods calls:

$users = collect([10, 20, 30, 40]);
 
return $this->setDefaultSuccessResponse([])->respondWithSuccess($users);

Or

public function __construct()
{
$this->setDefaultSuccessResponse([]);
}
 
...
 
$users = collect([10, 20, 30, 40]);
 
return $this->respondWithSuccess($users);

Related Content on Laravel Daily

Video

Recent Courses on Laravel Daily

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.