mohamed-ahmed / api-response
Reusable trait for standardized API responses
Installs: 30
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/mohamed-ahmed/api-response
Requires
- php: ^8.2
- illuminate/support: ^10.0 || ^11.0 || ^12.0
This package is not auto-updated.
Last update: 2025-10-24 18:42:30 UTC
README
A reusable Laravel package for building consistent JSON API responses.
It helps you standardize your API outputs with data, pagination, exceptions, and error structures — cleanly and efficiently.
Package info
URL: https://packagist.org/packages/mohamedahmed/api-response
📦 Installation
composer require mohamedahmed/api-response
🚀 Usage
Changelog
v2.0.0
- Added
DataTraitfor handling response data. - Added
PaginationTraitwith support for Laravel pagination. - Enabled method chaining:
->paginate($paginator) - Enabled method chaining:
->messages([...])->add($message)->merge([messages]) - Enabled method chaining:
->errors([...])->add($serror)->merge([errors]) - Enabled method chaining:
->alerts([...])->add($alert)->merge([alerts])
In your Laravel controller:
use MohamedAhmed\ApiResponse\Traits\ResponseApi; class SomeController extends Controller { use ResponseApi; public function index() { $this->setData(SomeModel::all()); return $this->apiResponse(); } } ### v2.0.0 $res = Response::make();
🧠 Available Methods
setData($data)
Sets the main response data.
If data is paginated, pagination details are auto-included.
$this->setData(User::all()); $this->setData(User::paginate(10)); ### v2.0.0 $res->data($items->items()); $res->paginate($items);
setException(Throwable $exception)
Stores an exception and adds error info in the response.
try {
// logic
} catch (\Exception $e) {
$this->setException($e);
$this->setCode(500);
return $this->apiResponse();
}
### v2.0.0
$res->exception($e);
return $this->tojson();
setEc(int $code)
Sets an internal error code, useful for debugging and frontend error mapping.
$this->setEc(1001); // Internal reference code
setMessages(array|string $messages)
Custom messages for the user.
$this->setMessages(['Created successfully']); ### v2.0.0 $res->nessages(['Created successfully']); // for alerts and errors also $res->add('additional message); $res->merge('[more of messages]);
setCode(int $httpCode)
Sets HTTP status code (defaults to 200).
$this->setCode(201); // HTTP Created ### v2.0.0 $res->code(201);
apiResponse()
Builds and returns the full JSON response.
return $this->apiResponse(); ### v2.0.0 return $res->tojson();
✅ Example Response
{
"code": 200,
"responseStatus": true,
"messages": [],
"response": {
"dataLength": 3,
"pagination": {
"path": "/api/products?page=1",
"total": 50,
"perPage": 10,
"currentPage": 1,
"lastPage": 5
},
"data": [{}, {}, {}]
},
"error": {
"errorCode": null,
"line": null,
"errorMessage": null,
"file": null
}
}