DEV Community

Netsai
Netsai

Posted on

Laravel API Response Helpers

A simple package allowing for consistent API responses throughout your Laravel application.
Install the package:
composer require f9webltd/laravel-api-response-helpers

<?php

namespace App\Http\Api\Controllers;

use F9Web\ApiResponseHelpers;
use Illuminate\Http\JsonResponse;

class OrdersController
{
    use ApiResponseHelpers;

    public function index(): JsonResponse
    {
        return $this->respondWithSuccess();
    }
}
Enter fullscreen mode Exit fullscreen mode

Other Methods that can be used

respondNotFound(string|Exception $message, ?string $key = 'error')
Enter fullscreen mode Exit fullscreen mode

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

`respondWithSuccess(array|Arrayable|JsonSerializable|null $contents = null)`
Enter fullscreen mode Exit fullscreen mode

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

respondOk(string $message)
Enter fullscreen mode Exit fullscreen mode

Returns a 200 HTTP status code

respondUnAuthenticated(?string $message = null)
Enter fullscreen mode Exit fullscreen mode

Returns a 401 HTTP status code


respondForbidden(?string $message = null)
Enter fullscreen mode Exit fullscreen mode

Returns a 403 HTTP status code

respondError(?string $message = null)
Enter fullscreen mode Exit fullscreen mode

Returns a 400 HTTP status code

respondCreated(array|Arrayable|JsonSerializable|null $data = null)
Enter fullscreen mode Exit fullscreen mode

Returns a 201 HTTP status code, with response optional data

Top comments (0)