A package for optimizing and unifying the response of laravel API
osama-98/laravel-response-api is a Laravel package for a package for optimizing and unifying the response of laravel api.
It currently has 11 GitHub stars and 652 downloads on Packagist (latest version 2.0.1).
Install it with composer require osama-98/laravel-response-api.
Discover more Laravel packages by osama-98
or browse all Laravel packages to compare alternatives.
Last updated
A Laravel package that provides a fluent and expressive interface for creating standardized JSON API responses.
You can install the package via composer:
composer require osama-98/laravel-response-api
| Package | Laravel | PHP | |---------|---------|-----| | 2.x | 12.x | ^8.3 | | 1.x | 10.x | 11.x | ^8.1 |
All responses follow this standardized JSON structure:
{
"message": "Human-readable message",
"body": {
// Response data (optional)
},
"errors": {
// Validation or error details (optional)
}
}
return ApiResponse::success(
data: ['user' => $user],
message: 'User retrieved successfully'
);
Response:
{
"message": "User retrieved successfully",
"body": {
"user": {
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
}
}
return ApiResponse::error(
message: 'Validation failed.',
errors: $validator->errors()->toArray()
);
Response:
{
"message": "Validation failed.",
"errors": {
"email": [
"The email field must be a valid email address.",
"The selected email is invalid."
]
}
}
return ApiResponse::pagination(
paginator: User::paginate(10),
mapper: UserResource::class
);
return ApiResponse::pagination(paginator: User::paginate(10), mapper: fn(User $user) => [
'id' => $user->id,
'name' => $user->name
]);
For more complex responses, use the fluent builder:
return ApiResponse::builder()
->data(['key' => 'value'])
->message('Custom message')
->errors(['field' => 'error message'])
->status(Response::HTTP_BAD_REQUEST)
->send();
composer test
This runs:
If you discover any security-related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.