PHPackages                             rawnoq/laravel-api-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. [HTTP &amp; Networking](/categories/http)
4. /
5. rawnoq/laravel-api-response

ActiveLibrary[HTTP &amp; Networking](/categories/http)

rawnoq/laravel-api-response
===========================

A professional Laravel package for standardized API responses with customizable keys and helper functions

1.0.0(5mo ago)0681MITPHPPHP ^8.2

Since Nov 12Pushed 5mo agoCompare

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

READMEChangelogDependencies (4)Versions (2)Used By (1)

Laravel API Response
====================

[](#laravel-api-response)

A professional Laravel package for standardized API responses with customizable keys and helper functions.

📦 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require rawnoq/laravel-api-response
```

The package will automatically register its service provider.

🚀 Features
----------

[](#-features)

- **Standardized API Responses**: Consistent JSON response structure across your application
- **Customizable Keys**: Configure response keys (status, data, message, etc.)
- **Helper Function**: Easy-to-use `respond()` helper function
- **Pagination Support**: Automatic pagination handling for paginated resources
- **HTTP Status Codes**: Pre-built methods for common HTTP status codes
- **Flexible Messages**: Support for single messages or arrays of messages
- **Type-Safe**: Full type hints and return types

📖 Usage
-------

[](#-usage)

### Basic Usage

[](#basic-usage)

```
use function respond;

// Success response
return respond()->success($data, 'Operation successful');

// Error response
return respond()->error('Something went wrong', null, 400);

// Custom response
return respond()->response($data, 'Custom message', 200, true, 'custom-action');
```

### Helper Function

[](#helper-function)

The package provides a global `respond()` helper function:

```
// In your controller
public function index()
{
    $users = User::all();
    return respond()->success($users, 'Users retrieved successfully');
}

public function store(Request $request)
{
    $user = User::create($request->validated());
    return respond()->created($user, 'User created successfully');
}

public function show($id)
{
    $user = User::findOrFail($id);
    return respond()->ok('User retrieved successfully', $user);
}
```

### HTTP Status Codes

[](#http-status-codes)

The package provides pre-built methods for common HTTP status codes:

```
// 200 OK
return respond()->ok('Operation successful', $data);

// 201 Created
return respond()->created($data, 'Resource created successfully');

// 202 Accepted
return respond()->accepted('Request accepted', $data);

// 204 No Content
return respond()->noContent('Resource deleted successfully');

// 400 Bad Request
return respond()->badRequest('Invalid request data');

// 401 Unauthorized
return respond()->unauthorized('Authentication required');

// 403 Forbidden
return respond()->forbidden('Access denied');

// 404 Not Found
return respond()->notFound('Resource not found');

// 409 Conflict
return respond()->conflict('Resource already exists');

// 422 Unprocessable Entity
return respond()->unprocessableEntity('Validation failed', $errors);

// 429 Too Many Requests
return respond()->tooManyRequests('Rate limit exceeded');

// 500 Internal Server Error
return respond()->internalServerError('An error occurred');

// 502 Bad Gateway
return respond()->badGateway('Bad gateway');

// 503 Service Unavailable
return respond()->serviceUnavailable('Service temporarily unavailable');

// 504 Gateway Timeout
return respond()->gatewayTimeout('Gateway timeout');
```

### Pagination Support

[](#pagination-support)

The package automatically handles paginated resources:

```
public function index()
{
    $users = User::paginate(15);
    return respond()->success($users, 'Users retrieved successfully');
}
```

This will automatically include pagination metadata in the response:

```
{
    "status": true,
    "code": 200,
    "action": "success",
    "message": "Users retrieved successfully",
    "data": [...],
    "pagination": {
        "total": 100,
        "per_page": 15,
        "current_page": 1,
        "last_page": 7,
        "from": 1,
        "to": 15,
        "links": {
            "current": "http://example.com/api/users?page=1",
            "first": "http://example.com/api/users?page=1",
            "last": "http://example.com/api/users?page=7",
            "prev": null,
            "next": "http://example.com/api/users?page=2"
        }
    }
}
```

### Customizing Response Keys

[](#customizing-response-keys)

You can customize the response keys by creating a new instance with custom keys:

```
$respond = new \Rawnoq\ApiResponse\Support\Respond(
    status_key: 'success',
    enable_status_key: true,
    data_key: 'payload',
    message_key: 'msg',
    messages_key: 'errors'
);

return $respond->success($data, 'Operation successful');
```

Or use the helper function with configuration:

```
$respond = respond();
$respond->status_key = 'success';
$respond->data_key = 'payload';
$respond->message_key = 'msg';

return $respond->success($data, 'Operation successful');
```

### Array Messages

[](#array-messages)

You can pass arrays of messages:

```
return respond()->error([
    'Email is required',
    'Password must be at least 8 characters'
], null, 422);
```

This will include both `message` (first message) and `messages` (all messages) in the response:

```
{
    "status": false,
    "code": 422,
    "action": "error",
    "message": "Email is required",
    "messages": [
        "Email is required",
        "Password must be at least 8 characters"
    ]
}
```

⚙️ Configuration
----------------

[](#️-configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=api-response-config
```

This will create `config/api-response.php`:

```
return [
    'status_key' => 'status',
    'enable_status_key' => true,
    'data_key' => 'data',
    'message_key' => 'message',
    'messages_key' => 'messages',
];
```

📋 Response Structure
--------------------

[](#-response-structure)

### Success Response

[](#success-response)

```
{
    "status": true,
    "code": 200,
    "action": "success",
    "message": "Operation successful",
    "data": {...}
}
```

### Error Response

[](#error-response)

```
{
    "status": false,
    "code": 400,
    "action": "error",
    "message": "Something went wrong",
    "data": null
}
```

### Paginated Response

[](#paginated-response)

```
{
    "status": true,
    "code": 200,
    "action": "success",
    "message": "Data retrieved successfully",
    "data": [...],
    "pagination": {
        "total": 100,
        "per_page": 15,
        "current_page": 1,
        "last_page": 7,
        "from": 1,
        "to": 15,
        "links": {
            "current": "http://example.com/api/users?page=1",
            "first": "http://example.com/api/users?page=1",
            "last": "http://example.com/api/users?page=7",
            "prev": null,
            "next": "http://example.com/api/users?page=2"
        }
    }
}
```

🎯 Available Methods
-------------------

[](#-available-methods)

### Core Methods

[](#core-methods)

- `response($data, $message, $code, $status, $action)` - Generic response method
- `success($data, $message, $code, $status, $action)` - Success response (200)
- `error($message, $data, $code, $status, $action)` - Error response (400)
- `ok($message, $data, $code, $status, $action)` - OK response (200)

### HTTP Status Code Methods

[](#http-status-code-methods)

- `created($data, $message, $code, $status, $action)` - 201 Created
- `accepted($message, $data, $code, $status, $action)` - 202 Accepted
- `noContent($message, $code, $status, $action)` - 204 No Content
- `badRequest($message, $data, $code, $status, $action)` - 400 Bad Request
- `unauthorized($message, $data, $code, $status, $action)` - 401 Unauthorized
- `forbidden($message, $data, $code, $status, $action)` - 403 Forbidden
- `notFound($message, $data, $code, $status, $action)` - 404 Not Found
- `methodNotAllowed($message, $data, $code, $status, $action)` - 405 Method Not Allowed
- `conflict($message, $data, $code, $status, $action)` - 409 Conflict
- `gone($message, $data, $code, $status, $action)` - 410 Gone
- `lengthRequired($message, $data, $code, $status, $action)` - 411 Length Required
- `preconditionFailed($message, $data, $code, $status, $action)` - 412 Precondition Failed
- `unprocessableEntity($message, $data, $code, $status, $action)` - 422 Unprocessable Entity
- `tooManyRequests($message, $data, $code, $status, $action)` - 429 Too Many Requests
- `internalServerError($message, $data, $code, $status, $action)` - 500 Internal Server Error
- `badGateway($message, $data, $code, $status, $action)` - 502 Bad Gateway
- `serviceUnavailable($message, $data, $code, $status, $action)` - 503 Service Unavailable
- `gatewayTimeout($message, $data, $code, $status, $action)` - 504 Gateway Timeout
- `notImplemented($message, $data, $code, $status, $action)` - 501 Not Implemented

🔧 Examples
----------

[](#-examples)

### Controller Example

[](#controller-example)

```
