A Laravel package that provides a standardized, consistent way to format API responses with proper status codes, messages, and error handling.
- Modern PHP 8.0+ implementation with type hints and return types
- Consistent JSON response structure
- Automatic handling of Laravel Models, Collections, and Paginated responses
- Configurable resource naming for collections
- Comprehensive exception handling
- Debug mode with stack traces
- Support for custom headers and messages
Install the package via composer:
composer require faridibin/laravel-api-response
Publish the configuration file:
php artisan vendor:publish --tag="api-response-config"
The config/api-response.php
file includes:
return [
// Exception handlers
'exceptions' => [
ModelNotFoundException::class => [
'setStatusCode' => 404,
'setModelNotFoundMessage' => 'Resource not found'
],
ValidationException::class => function($exception, $handler) {
$handler
->setStatusCode(422)
->setMessage('Validation failed')
->mergeErrors($exception->errors());
}
],
// Enable stack traces in local environment
'trace' => env('APP_ENV') === 'local',
// Use plural resource names for collections
'resource_name' => true,
];
Add the middleware to your API routes in app/Http/Kernel.php
:
protected $middlewareGroups = [
'api' => [
\Faridibin\LaravelApiResponse\Http\Middleware\EnsureApiResponse::class,
],
];
The package provides a consistent response structure:
{
"data": {},
"message": "Optional message",
"errors": [],
"success": true,
"status": "success",
"status_code": 200,
"status_text": "OK"
}
public function show(User $user)
{
return $user;
}
Response:
{
"data": {
"user": {
"id": 1,
"name": "Crystal Farrell",
"email": "[email protected]",
"email_verified_at": "2025-02-02T02:20:17.000000Z",
"created_at": "2025-02-02T02:20:17.000000Z",
"updated_at": "2025-02-02T02:20:17.000000Z"
}
},
"errors": [],
"success": true,
"status": "success",
"status_code": 200,
"status_text": "OK"
}
public function index()
{
return User::all();
}
Response includes automatically pluralized resource name:
{
"data": {
"users": [
{
"id": 1,
"name": "Crystal Farrell",
"email": "[email protected]",
"email_verified_at": "2025-02-02T02:20:17.000000Z",
"created_at": "2025-02-02T02:20:17.000000Z",
"updated_at": "2025-02-02T02:20:17.000000Z"
}
]
},
"success": true,
"status": "success",
"status_code": 200,
"status_text": "OK"
}
public function index()
{
return User::paginate();
}
Key changes when upgrading from the previous version:
-
Namespace Change:
- Old:
Faridibin\LaravelJsonResponse
- New:
Faridibin\LaravelApiResponse
- Old:
-
Middleware:
- Old:
OutputJsonResponse
- New:
EnsureApiResponse
- Old:
-
Trait:
- Old:
HasJson
- New:
HasApiResponse
- Old:
-
Method Changes:
// Old json_response()->error('message'); // New $this->setMessage('message')->mergeErrors(['error']);
-
Response Not Formatting
// Ensure middleware is registered correctly in Kernel.php protected $middlewareGroups = [ 'api' => [ \Faridibin\LaravelApiResponse\Http\Middleware\EnsureApiResponse::class, ], ];
-
Resource Names Not Working
// Verify config/api-response.php has: 'resource_name' => true,
-
Exception Handler Not Working
// Check exception configuration: 'exceptions' => [ YourException::class => [ 'setStatusCode' => 404, 'setMessage' => 'Custom message' ] ]
-
Stack Traces Not Showing
- Ensure your environment is set to 'local'
- Check
trace
config is enabled
Contributions are welcome! Please feel free to submit a Pull Request.
This package is open-sourced software licensed under the MIT license.