PHPackages                             arpanpatoliya/response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. arpanpatoliya/response

ActiveLibrary[API Development](/categories/api)

arpanpatoliya/response
======================

A simple Laravel package for standardized API responses

v1.1(5mo ago)24125MITPHPPHP ^8.0

Since Jun 27Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/arpanpatoliya/response)[ Packagist](https://packagist.org/packages/arpanpatoliya/response)[ Docs](https://github.com/arpanpatoliya/response)[ RSS](/packages/arpanpatoliya-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (3)Used By (0)

Laravel Response Package
========================

[](#laravel-response-package)

[![Latest Version](https://camo.githubusercontent.com/7e8496e16aba8153b2990b30af8f37312de38d06b384acca047bdc915a204d4a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f617270616e7061746f6c6979612f726573706f6e73652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/arpanpatoliya/response)[![License](https://camo.githubusercontent.com/2640d1b9145a16dbf4cdc7d1a1536c3146be549c78ddf5e55974908ea4b3aedf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f617270616e7061746f6c6979612f726573706f6e73652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

A comprehensive Laravel package for standardized API responses with full HTTP status code coverage and response macros.

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#-features)
- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Usage](#-usage)
- [HTTP Status Codes](#-http-status-codes)
- [Response Format](#-response-format)
- [Examples](#-examples)
- [Testing](#-testing)
- [Contributing](#-contributing)
- [License](#-license)

✨ Features
----------

[](#-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
- 📝 **Logging Integration** - Chainable logging for responses
- 🧪 **Fully Tested** - Comprehensive test coverage
- 📚 **Well Documented** - Complete documentation and examples
- ⚡ **Lightweight** - Minimal overhead, maximum functionality

🛠️ Installation
---------------

[](#️-installation)

1. Install the package via Composer:

```
composer require arpanpatoliya/response
```

2. The service provider will be automatically registered via Laravel's package discovery.

🚀 Quick Start
-------------

[](#-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
-------

[](#-usage)

### Basic Success Responses

[](#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

[](#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-responses)

```
// Validation failure (422)
return response()->validationFailure($validator);
```

### Advanced Responses

[](#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();
```

### Logging Integration

[](#logging-integration)

The package provides a chainable `log()` method to log responses to Laravel's logging system. By default, logs are written to the default logging channel.

```
// Basic logging (default channel, info level)
return response()->success('User created', $user)->log();

// With custom channel
return response()->success('User created', $user)->log('custom-channel');

// With channel and custom log level
return response()->success('User created', $user)->log('custom-channel', 'warning');

// With channel, level, and custom message
return response()->success('User created', $user)->log('custom-channel', 'info', 'User was created successfully', ['actor' => auth()->id()]);

// With just level (default channel)
return response()->success('User created', $user)->log(null, 'error');

// With just custom message (default channel, info level)
return response()->success('User created', $user)->log(null, null, 'Custom log message');

// Logging error responses
return response()->notFound('User not found')->log('api-errors', 'warning');

// Logging validation failures
return response()->validationFailure($validator)->log('validation', 'info');
```

**Log Parameters:**

- `$channel` (optional): Specify a custom logging channel. If not provided, uses the default channel.
- `$level` (optional): PSR-3 log level (`emergency`, `alert`, `critical`, `error`, `warning`, `notice`, `info`, `debug`). Defaults to `info`.
- `$message` (optional): Custom log message. Defaults to `'API response'`.
- `$context` (optional): Additional context array to include in the log entry.

**Log Context:**The log automatically includes:

- `status`: HTTP status code
- `payload`: Response payload/data
- Any additional context you pass

🌐 HTTP Status Codes
-------------------

[](#-http-status-codes)

### 1xx Informational

[](#1xx-informational)

MacroStatusDescription`continue()`100Continue`switchingProtocols()`101Switching Protocols`processing()`102Processing`earlyHints()`103Early Hints### 2xx Success

[](#2xx-success)

MacroStatusDescription`ok()`200OK`success()`200Success with data`successMessage()`200Success message only`created()`201Created`accepted()`202Accepted`nonAuthoritativeInformation()`203Non-Authoritative Information`noContent()`204No Content`resetContent()`205Reset Content`partialContent()`206Partial Content`multiStatus()`207Multi-Status`alreadyReported()`208Already Reported`imUsed()`226IM Used### 3xx Redirection

[](#3xx-redirection)

MacroStatusDescription`multipleChoices()`300Multiple Choices`movedPermanently()`301Moved Permanently`found()`302Found`seeOther()`303See Other`notModified()`304Not Modified`useProxy()`305Use Proxy`temporaryRedirect()`307Temporary Redirect`permanentRedirect()`308Permanent Redirect### 4xx Client Errors

[](#4xx-client-errors)

MacroStatusDescription`badRequest()`400Bad Request`unauthorized()`401Unauthorized`paymentRequired()`402Payment Required`forbidden()`403Forbidden`notFound()`404Not Found`methodNotAllowed()`405Method Not Allowed`notAcceptable()`406Not Acceptable`proxyAuthenticationRequired()`407Proxy Authentication Required`requestTimeout()`408Request Timeout`conflict()`409Conflict`gone()`410Gone`lengthRequired()`411Length Required`preconditionFailed()`412Precondition Failed`payloadTooLarge()`413Payload Too Large`uriTooLong()`414URI Too Long`unsupportedMediaType()`415Unsupported Media Type`rangeNotSatisfiable()`416Range Not Satisfiable`expectationFailed()`417Expectation Failed`imATeapot()`418I'm a teapot`misdirectedRequest()`421Misdirected Request`unprocessableEntity()`422Unprocessable Entity`locked()`423Locked`failedDependency()`424Failed Dependency`tooEarly()`425Too Early`upgradeRequired()`426Upgrade Required`preconditionRequired()`428Precondition Required`tooManyRequests()`429Too Many Requests`requestHeaderFieldsTooLarge()`431Request Header Fields Too Large`unavailableForLegalReasons()`451Unavailable For Legal Reasons### 5xx Server Errors

[](#5xx-server-errors)

MacroStatusDescription`internalServerError()`500Internal Server Error`serverError()`500Server Error (alias)`notImplemented()`501Not Implemented`badGateway()`502Bad Gateway`serviceUnavailable()`503Service Unavailable`gatewayTimeout()`504Gateway Timeout`httpVersionNotSupported()`505HTTP Version Not Supported`variantAlsoNegotiates()`506Variant Also Negotiates`insufficientStorage()`507Insufficient Storage`loopDetected()`508Loop Detected`notExtended()`510Not Extended`networkAuthenticationRequired()`511Network Authentication Required### Utility Methods

[](#utility-methods)

MacroStatusDescription`errorMessage()`200Basic error message`error()`VariableError with custom status`validationFailure()`422Validation errors`custom()`VariableCustom response`paginated()`200Paginated response`withMeta()`200Response with metadata`updated()`200Resource updated`deleted()`200Resource deleted### Logging Method

[](#logging-method)

MethodDescription`log()`Chainable logging method for responses. Supports custom channel, level, message, and context.📄 Response Format
-----------------

[](#-response-format)

### Success Response

[](#success-response)

```
{
    "status": true,
    "message": "Success message",
    "data": {} // Optional data
}
```

### Error Response

[](#error-response)

```
{
    "status": false,
    "message": "Error message",
    "errors": {} // For validation errors
}
```

### Paginated Response

[](#paginated-response)

```
{
    "status": true,
    "message": "Success message",
    "data": [],
    "pagination": {
        "current_page": 1,
        "per_page": 10,
        "total": 100
    }
}
```

### Response with Metadata

[](#response-with-metadata)

```
{
    "status": true,
    "message": "Success message",
    "data": [],
    "meta": {
        "version": "1.0",
        "timestamp": 1234567890
    }
}
```

💡 Examples
----------

[](#-examples)

### Complete User Controller Example

[](#complete-user-controller-example)

```
