Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

Laravel Api Response Helpers

f9webltd/laravel-api-response-helpers image

Laravel Api Response Helpers stats

Downloads
110.5K
Stars
572
Open Issues
5
Forks
50

View on GitHub →

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

Laravel API Response Helpers

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

Requirements

  • PHP ^7.4 | ^8.0
  • Laravel 6, 7, 8, 9 or 10

Installation / Usage

composer require f9webltd/laravel-api-response-helpers

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);

Use with additional object types

In addition to a plain PHP array, the following data types can be passed to relevant methods:

  • Objects implementing the Laravel Illuminate\Contracts\Support\Arrayable contract
  • Objects implementing the native PHP JsonSerializable contract

This allows a variety of object types to be passed and converted automatically.

Below are a few common object types that can be passed.

Laravel Collections - Illuminate\Support\Collection

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

Laravel Eloquent Collections - Illuminate\Database\Eloquent\Collection

$invoices = Invoice::pending()->get();
 
return $this->respondWithSuccess($invoices);

Laravel API Resources - Illuminate\Http\Resources\Json\JsonResource

This package is intended to be used alongside Laravel's API resources and in no way replaces them.

$resource = PostResource::make($post);
 
return $this->respondCreated($resource);

Motivation

Ensure consistent JSON API responses throughout an application. The motivation was primarily based on a very old inherited Laravel project. The project contained a plethora of methods/structures used to return an error:

  • response()->json(['error' => $error], 400)
  • response()->json(['data' => ['error' => $error], 400)
  • response()->json(['message' => $error], Response::HTTP_BAD_REQUEST)
  • response()->json([$error], 400)
  • etc.

I wanted to add a simple trait that kept this consistent, in this case:

$this->respondError('Ouch')

Contribution

Any ideas are welcome. Feel free to submit any issues or pull requests.

Testing

composer test

Security

If you discover any security related issues, please email rob@f9web.co.uk instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


F9Webltd Laravel Api Response Helpers Related Articles

Passage: A Lightweight API Proxy Gateway for Laravel image

Passage: A Lightweight API Proxy Gateway for Laravel

Read article
The Inertia v3 Beta is Here image

The Inertia v3 Beta is Here

Read article
Meet LaraUtilX: A Utility Toolkit Every Laravel Developer Needs image

Meet LaraUtilX: A Utility Toolkit Every Laravel Developer Needs

Read article
Accelerate API Testing with Laravel's ddBody() Method image

Accelerate API Testing with Laravel's ddBody() Method

Read article
Running a Single Test, Skipping Tests, and Other Tips and Tricks image

Running a Single Test, Skipping Tests, and Other Tips and Tricks

Read article
Write API Integrations and SDKs in an Elegant Way image

Write API Integrations and SDKs in an Elegant Way

Read article
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
CodeKudu logo

CodeKudu

Stand-ups, Retrospectives, and 360° Feedback for the entire team. 50% off with code LARAVELNEWS.

CodeKudu
Typesense Search logo

Typesense Search

Typesense is an open source, blazing-fast search engine, optimized for helping you build delightful search experiences for your sites and apps. Natively integrated with Laravel Scout.

Typesense Search
Celebian logo

Celebian

Celebian is a social media marketing agency specializing in helping their clients go viral on TikTok. Whether you're looking to reach a bigger audience or gain more Tiktok followers, likes, and views, they've got you covered.

Celebian
Securing Laravel logo

Securing Laravel

The essential security resource for Laravel devs, covering everything you need to keep your apps secure. Sign up to receive weekly security tips and monthly in depth articles, diving deep into security concepts you need to know!

Securing Laravel