Looking to hire Laravel developers? Try LaraJobs

laravel-api-response maintained by drdre4life2

Description
A simple JSON response helper for Laravel 10+
Author
Last update
2025/04/02 15:12 (dev-main)
License
Links
Downloads
72

Comments
comments powered by Disqus

Laravel API Response Package

Introduction

This package provides a standardized way to return JSON responses in Laravel applications. It simplifies response handling for success, validation, client errors, and server errors.

Installation

Install the package via Composer:

composer require drdre4life2/api-response

Usage

Include the Trait

Add the HasApiResponse trait to your base Controller:

namespace App\Http\Controllers;

use Drdre4life2\ApiResponse\Traits\HasApiResponse;


abstract class Controller
{
    use HasApiResponse;

}

Available Methods

Success Responses

return $this->okResponse('Success message', ['key' => 'value']);
return $this->createdResponse('Resource created', ['id' => 1]);
return $this->noContentResponse();

Client Error Responses

return $this->badRequestResponse('Invalid request', ['error' => 'Details']);
return $this->unauthenticatedResponse('Unauthorized');
return $this->forbiddenResponse('Access denied');
return $this->notFoundResponse('Resource not found');

Server Error Responses

return $this->serverErrorResponse('Server error occurred');

Example in a Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ExampleController extends Controller
{
    public function index(Request $request)
    {
        $data = ['message' => 'Hello, World!'];
        return $this->okResponse('Data retrieved successfully', $data);
    }
}

Testing

Run the test suite with:

php artisan test

License

This package is open-source software licensed under the MIT License.