hiteshpadhara/laravel-response-macro

Adds a Response::api() macro for uniform JSON APIs

dev-main 2025-04-21 10:16 UTC

This package is auto-updated.

Last update: 2025-06-21 10:40:31 UTC


README

Packagist Version Build Status License

Add a Response::api() macro for uniform JSON API responses in Laravel.

Installation

Install the package via Composer:

composer require hiteshpadhara/laravel-response-macro

Laravel ≥10 will auto-discover the service provider. For older versions, register it manually:

// config/app.php
'providers' => [
    // ...
    hiteshpadhara\ResponseMacro\ResponseMacroServiceProvider::class,
];

Usage

Use the macro in your controllers or routes:

use Illuminate\Support\Facades\Response;

return Response::api(200, 'Success', [
    'user' => $user
]);

Generates:

{
  "status": 200,
  "message": "Success",
  "data": {
    "user": { /* ... */ }
  }
}

If the $data parameter is null, the data key is omitted.

Configuration

Publish the config to customize response keys:

php artisan vendor:publish --tag=config

Modify config/response.php:

return [
    'status_key'  => 'status',
    'message_key' => 'message',
    'data_key'    => 'data',
];

Testing

Run the package tests using PHPUnit and Testbench:

composer install
vendor/bin/phpunit

Contributing

  1. Fork the repository.
  2. Create your feature branch: git checkout -b feature/YourFeature.
  3. Commit your changes: git commit -m 'Add some feature'.
  4. Push to the branch: git push origin feature/YourFeature.
  5. Submit a pull request.

Licensing

This package is open-sourced software licensed under the MIT license.