amirali-hossaini / laravel-api-response
Consistent JSON API responses for Laravel, with resource transformation, pagination, and standardized error formatting.
Package info
github.com/amirali-hossaini/laravel-api-response
pkg:composer/amirali-hossaini/laravel-api-response
Requires
- php: ^8.3
- illuminate/contracts: ^13.0
- illuminate/http: ^13.0
- illuminate/support: ^13.0
Requires (Dev)
- laravel/pint: ^1.0
- orchestra/testbench: ^11.0
- phpunit/phpunit: ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A small Laravel trait for consistent JSON responses, API resources, and pagination.
{
"data": {"id": 1, "name": "Example"},
"message": "Item created.",
"errors": []
}
Requirements
- PHP 8.3 or later within the PHP 8 series
- Laravel 13
Installation
Install the package via Composer:
composer require amirali-hossaini/laravel-api-response
Import the trait in your controller. No service provider, configuration publishing, or migrations are needed.
<?php namespace App\Http\Controllers; use AmiraliHossaini\LaravelApiResponse\Traits\ApiResponse; use Illuminate\Http\JsonResponse; class ExampleController extends Controller { use ApiResponse; public function show(): JsonResponse { return $this ->message('Item retrieved.') ->data(['id' => 1, 'name' => 'Example']) ->successResponse(); } }
The response helpers are protected: call them from your controller actions. You can also add the trait to your application's base controller to share it with child controllers.
Response helpers
Use data($value) to set the payload for a success or error response. The payload defaults to null when no data is provided.
| Method | Default status | Default message |
|---|---|---|
successResponse($statusCode = 200) |
200 | Empty string |
createdResponse($statusCode = 201) |
201 | Empty string |
paymentRequiredResponse($statusCode = 402) |
402 | Empty string |
errorResponse($statusCode = 400) |
400 | Empty string |
validationErrorResponse() |
422 | Validation failed. |
notFoundResponse() |
404 | Not found. |
unauthorizedResponse() |
401 | Unauthenticated. |
forbiddenResponse() |
403 | Forbidden. |
serverErrorResponse() |
500 | Server error. |
For custom data, errors, and HTTP status:
return $this ->data(['version' => 2]) ->errors(['version' => ['This record has changed.']]) ->apiResponse(statusCode: 409);
Messages and errors
Use errors($errors) to attach error details to the response. Errors default to an empty array.
return $this ->message('Please correct the highlighted fields.') ->errors([ 'email' => ['The email address is invalid.'], ]) ->validationErrorResponse();
{
"data": null,
"message": "Please correct the highlighted fields.",
"errors": {"email": ["The email address is invalid."]}
}
Default error messages use Laravel's translation helper with English source strings. Translate them in your application's JSON language files, or supply your own translated message:
return $this->message(__('messages.item_missing'))->notFoundResponse();
An explicitly empty message stays empty.
The package formats responses you explicitly return. Laravel's automatic validation exceptions and other exception responses continue to use your application's exception handler.
API resources
Single model
return $this ->resource(UserResource::class) ->data($user) ->successResponse();
You can also pass a resource instance directly:
return $this->data(new UserResource($user))->successResponse();
Both produce:
{
"data": {
"id": 1,
"name": "Example"
},
"message": "",
"errors": []
}
The resource's transformed fields appear directly in data. A null payload stays null, even if a resource class has been selected.
Collections
return $this ->resource(UserResource::class) ->data($users) ->successResponse();
You can also pass a resource collection directly:
return $this ->data(UserResource::collection($users)) ->successResponse();
Both produce:
{
"data": {"items": [{"id": 1, "name": "Example"}]},
"message": "",
"errors": []
}
When a resource class is selected, arrays and Laravel collections are treated as lists. For a single associative array, wrap it in a resource instance. Without a resource, data is passed through unchanged.
Resources are resolved inside this package's envelope. Their field transformations and conditional fields are supported; Laravel resource-level wrapping, additional() metadata, and withResponse() hooks are not applied.
Pagination
Use Laravel's paginate() with a resource:
return $this ->resource(UserResource::class) ->data(User::query()->paginate(15)) ->successResponse();
You can also pass a paginated resource collection directly:
return $this ->data(UserResource::collection(User::query()->paginate(15))) ->successResponse();
Both approaches produce the same structure:
{
"data": {
"items": [{"id": 1, "name": "Example"}],
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"per_page": 15,
"to": 1,
"total": 1
},
"links": {
"first": "https://example.com/users?page=1",
"last": "https://example.com/users?page=1",
"prev": null,
"next": null
}
},
"message": "",
"errors": []
}
The custom pagination format supports LengthAwarePaginator (paginate()). It does not define a custom format for simplePaginate() or cursorPaginate(). Passing a paginator without a resource preserves Laravel's own serialized data structure.
Response state
data(), message(), errors(), and resource() apply to the next response only. The trait automatically resets all four before building the response, including when resource resolution fails. No manual cleanup is needed, and these values do not carry over to subsequent responses.
The trait declares private $data, $message, $errors, and $resource properties. Avoid declaring incompatible properties or methods with the same names in the consuming class.
License
MIT. See LICENSE.