DEV Community

Netsai
Netsai

Posted on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay