arpanpatoliya / response
A simple Laravel package for standardized API responses
Requires
- php: ^8.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.0|^10.0
README
A comprehensive Laravel package for standardized API responses with full HTTP status code coverage and response macros.
๐ Table of Contents
- Features
- Installation
- Quick Start
- Usage
- HTTP Status Codes
- Response Format
- Examples
- Testing
- Contributing
- License
โจ Features
- ๐ 76 Response Macros - Complete HTTP status code coverage
- ๐ Standardized Format - Consistent JSON response structure
- ๐ฏ Easy to Use - Simple, intuitive API
- ๐ง Flexible - Custom status codes and messages
- ๐ Validation Support - Built-in validation error handling
- ๐ฑ Pagination Support - Easy paginated responses
- ๐ท๏ธ Metadata Support - Add custom metadata to responses
- ๐งช Fully Tested - Comprehensive test coverage
- ๐ Well Documented - Complete documentation and examples
- โก Lightweight - Minimal overhead, maximum functionality
๐ ๏ธ Installation
- Install the package via Composer:
composer require arpanpatoliya/response
- The service provider will be automatically registered via Laravel's package discovery.
๐ Quick Start
// Basic success response return response()->success('User created successfully', $userData); // Error response return response()->notFound('User not found'); // Validation error return response()->validationFailure($validator); // Custom status code return response()->conflict('Resource already exists');
๐ Usage
Basic Success Responses
// Success with data (200) return response()->success('User created successfully', $userData); // Success message only (200) return response()->successMessage('User updated successfully'); // Resource created (201) return response()->created('User created successfully', $userData); // Resource updated (200) return response()->updated('User updated successfully', $userData); // Resource deleted (200) return response()->deleted('User deleted successfully'); // Accepted (202) return response()->accepted('Request accepted for processing');
Error Responses
// Basic error (200) return response()->errorMessage('User not found'); // Error with custom status code return response()->error('Bad request', 400); // HTTP status specific errors return response()->badRequest('Invalid input data'); return response()->unauthorized('Invalid credentials'); return response()->forbidden('Access denied'); return response()->notFound('User not found'); return response()->conflict('Resource already exists'); return response()->tooManyRequests('Rate limit exceeded'); return response()->serverError('Database connection failed');
Validation Responses
// Validation failure (422) return response()->validationFailure($validator);
Advanced Responses
// Custom response return response()->custom(true, 'Custom response', $data, 201); // Paginated response return response()->paginated('Users retrieved', $users, $pagination); // Response with metadata return response()->withMeta('Data retrieved', $data, $meta); // No content response (204) return response()->noContent();
๐ HTTP Status Codes
1xx Informational
Macro | Status | Description |
---|---|---|
continue() |
100 | Continue |
switchingProtocols() |
101 | Switching Protocols |
processing() |
102 | Processing |
earlyHints() |
103 | Early Hints |
2xx Success
Macro | Status | Description |
---|---|---|
ok() |
200 | OK |
success() |
200 | Success with data |
successMessage() |
200 | Success message only |
created() |
201 | Created |
accepted() |
202 | Accepted |
nonAuthoritativeInformation() |
203 | Non-Authoritative Information |
noContent() |
204 | No Content |
resetContent() |
205 | Reset Content |
partialContent() |
206 | Partial Content |
multiStatus() |
207 | Multi-Status |
alreadyReported() |
208 | Already Reported |
imUsed() |
226 | IM Used |
3xx Redirection
Macro | Status | Description |
---|---|---|
multipleChoices() |
300 | Multiple Choices |
movedPermanently() |
301 | Moved Permanently |
found() |
302 | Found |
seeOther() |
303 | See Other |
notModified() |
304 | Not Modified |
useProxy() |
305 | Use Proxy |
temporaryRedirect() |
307 | Temporary Redirect |
permanentRedirect() |
308 | Permanent Redirect |
4xx Client Errors
Macro | Status | Description |
---|---|---|
badRequest() |
400 | Bad Request |
unauthorized() |
401 | Unauthorized |
paymentRequired() |
402 | Payment Required |
forbidden() |
403 | Forbidden |
notFound() |
404 | Not Found |
methodNotAllowed() |
405 | Method Not Allowed |
notAcceptable() |
406 | Not Acceptable |
proxyAuthenticationRequired() |
407 | Proxy Authentication Required |
requestTimeout() |
408 | Request Timeout |
conflict() |
409 | Conflict |
gone() |
410 | Gone |
lengthRequired() |
411 | Length Required |
preconditionFailed() |
412 | Precondition Failed |
payloadTooLarge() |
413 | Payload Too Large |
uriTooLong() |
414 | URI Too Long |
unsupportedMediaType() |
415 | Unsupported Media Type |
rangeNotSatisfiable() |
416 | Range Not Satisfiable |
expectationFailed() |
417 | Expectation Failed |
imATeapot() |
418 | I'm a teapot |
misdirectedRequest() |
421 | Misdirected Request |
unprocessableEntity() |
422 | Unprocessable Entity |
locked() |
423 | Locked |
failedDependency() |
424 | Failed Dependency |
tooEarly() |
425 | Too Early |
upgradeRequired() |
426 | Upgrade Required |
preconditionRequired() |
428 | Precondition Required |
tooManyRequests() |
429 | Too Many Requests |
requestHeaderFieldsTooLarge() |
431 | Request Header Fields Too Large |
unavailableForLegalReasons() |
451 | Unavailable For Legal Reasons |
5xx Server Errors
Macro | Status | Description |
---|---|---|
internalServerError() |
500 | Internal Server Error |
serverError() |
500 | Server Error (alias) |
notImplemented() |
501 | Not Implemented |
badGateway() |
502 | Bad Gateway |
serviceUnavailable() |
503 | Service Unavailable |
gatewayTimeout() |
504 | Gateway Timeout |
httpVersionNotSupported() |
505 | HTTP Version Not Supported |
variantAlsoNegotiates() |
506 | Variant Also Negotiates |
insufficientStorage() |
507 | Insufficient Storage |
loopDetected() |
508 | Loop Detected |
notExtended() |
510 | Not Extended |
networkAuthenticationRequired() |
511 | Network Authentication Required |
Utility Methods
Macro | Status | Description |
---|---|---|
errorMessage() |
200 | Basic error message |
error() |
Variable | Error with custom status |
validationFailure() |
422 | Validation errors |
custom() |
Variable | Custom response |
paginated() |
200 | Paginated response |
withMeta() |
200 | Response with metadata |
updated() |
200 | Resource updated |
deleted() |
200 | Resource deleted |
๐ Response Format
Success Response
{ "status": true, "message": "Success message", "data": {} // Optional data }
Error Response
{ "status": false, "message": "Error message", "errors": {} // For validation errors }
Paginated Response
{ "status": true, "message": "Success message", "data": [], "pagination": { "current_page": 1, "per_page": 10, "total": 100 } }
Response with Metadata
{ "status": true, "message": "Success message", "data": [], "meta": { "version": "1.0", "timestamp": 1234567890 } }
๐ก Examples
Complete User Controller Example
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class UserController extends Controller { public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|min:8' ]); if ($validator->fails()) { return response()->validationFailure($validator); } try { $user = User::create($request->all()); return response()->created('User created successfully', $user); } catch (\Exception $e) { return response()->serverError('Failed to create user'); } } public function index(Request $request) { try { $users = User::paginate(10); return response()->paginated( 'Users retrieved successfully', $users->items(), [ 'current_page' => $users->currentPage(), 'per_page' => $users->perPage(), 'total' => $users->total(), 'last_page' => $users->lastPage() ] ); } catch (\Exception $e) { return response()->serverError('Failed to retrieve users'); } } public function show($id) { $user = User::find($id); if (!$user) { return response()->notFound('User not found'); } return response()->success('User retrieved successfully', $user); } public function update(Request $request, $id) { $user = User::find($id); if (!$user) { return response()->notFound('User not found'); } $validator = Validator::make($request->all(), [ 'name' => 'sometimes|string|max:255', 'email' => 'sometimes|email|unique:users,email,' . $id ]); if ($validator->fails()) { return response()->validationFailure($validator); } try { $user->update($request->all()); return response()->updated('User updated successfully', $user); } catch (\Exception $e) { return response()->serverError('Failed to update user'); } } public function destroy($id) { $user = User::find($id); if (!$user) { return response()->notFound('User not found'); } try { $user->delete(); return response()->deleted('User deleted successfully'); } catch (\Exception $e) { return response()->serverError('Failed to delete user'); } } public function bulkDelete(Request $request) { $ids = $request->input('ids', []); if (empty($ids)) { return response()->badRequest('No user IDs provided'); } try { $deletedCount = User::whereIn('id', $ids)->delete(); if ($deletedCount === 0) { return response()->notFound('No users found to delete'); } return response()->success("Successfully deleted {$deletedCount} users"); } catch (\Exception $e) { return response()->serverError('Failed to delete users'); } } }
Advanced Usage Examples
// Rate limiting if ($this->isRateLimited()) { return response()->tooManyRequests('Rate limit exceeded. Try again in 60 seconds.'); } // File upload validation if ($request->file('image')->getSize() > 5242880) { // 5MB return response()->payloadTooLarge('File size exceeds maximum limit of 5MB'); } // Maintenance mode if ($this->isMaintenanceMode()) { return response()->serviceUnavailable('System is under maintenance. Please try again later.'); } // Custom response with metadata return response()->withMeta( 'Data retrieved successfully', $data, [ 'version' => '1.0.0', 'timestamp' => now()->timestamp, 'cache_hit' => true ] ); // Partial content for large datasets return response()->partialContent('Partial data retrieved', $partialData); // Conflict resolution if ($this->hasConflict($data)) { return response()->conflict('Resource already exists with these parameters'); }
๐งช Testing
To run the tests for this package:
composer test
Or run PHPUnit directly:
./vendor/bin/phpunit
The tests cover all response macros, ensuring they return the correct status codes and response formats.
Test Coverage
- โ All HTTP status code macros (100+ methods)
- โ Response format validation
- โ Status code verification
- โ Error handling
- โ Validation responses
- โ Pagination responses
- โ Metadata responses
- โ Custom responses
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
- Fork the repository
- Clone your fork
- Install dependencies:
composer install
- Run tests:
composer test
- Make your changes
- Add tests for new features
- Submit a pull request
๐จโ๐ป Author
Arpan Patoliya
- Email: info.arpan08@gmail.com
- GitHub: @arpanpatoliya
- LinkedIn: Arpan Patoliya
About the Author
Arpan is a passionate Laravel developer with expertise in building robust and scalable web applications. This package was created to provide a comprehensive solution for standardized API responses in Laravel applications.
๐ License
The MIT License (MIT). Please see License File for more information.
Made with โค๏ธ by Arpan Patoliya
If you find this package helpful, please consider giving it a โญ on GitHub!