├── README.md
├── art
└── socialcard.png
├── composer.json
├── phpunit.xml
├── src
├── ApiResponse.php
├── ApiResponseServiceProvider.php
├── Config
│ └── api-response.php
├── Traits
│ └── HandlesApiExceptions.php
└── helpers.php
└── tests
├── ApiResponseTest.php
├── HandlesApiExceptionsTest.php
└── HelpersTest.php
/README.md:
--------------------------------------------------------------------------------
1 |
2 |

3 |
4 | # Laravel API Response Formatter
5 |
6 | [](https://packagist.org/packages/darshphpdev/laravel-api-response-formatter)
7 | [](https://packagist.org/packages/darshphpdev/laravel-api-response-formatter)
8 | [](https://packagist.org/packages/darshphpdev/laravel-api-response-formatter)
9 |
10 | A powerful Laravel package that standardizes your API responses with a clean, expressive syntax. Perfect for building consistent RESTful APIs.
11 |
12 | ## Features
13 |
14 | - 🚀 **Simple & Expressive API** - Fluent interface for building responses
15 | - 🎯 **Consistent Format** - Standardized response structure across your API
16 | - 📦 **Built-in Support** for:
17 | - Success/Error responses
18 | - Validation errors
19 | - Pagination
20 | - Custom headers
21 | - Exception handling
22 | - ⚙️ **Highly Configurable** - Customize keys, messages, and more
23 | - 🔒 **Type-Safe** - Full TypeScript-like safety with PHP 7.4+
24 | - 🧪 **Well Tested** - Comprehensive test coverage
25 |
26 | ## Quick Start
27 |
28 | ### Installation
29 |
30 | ```bash
31 | composer require darshphpdev/laravel-api-response-formatter
32 | ```
33 |
34 | ### Basic Usage
35 |
36 | ```php
37 | // Success Response
38 | return api_response()
39 | ->success()
40 | ->message('Welcome!')
41 | ->send(['name' => 'Laravel']);
42 |
43 | // Error Response
44 | return api_response()
45 | ->error()
46 | ->code(404)
47 | ->message('Resource Not Found')
48 | ->send();
49 |
50 | // With Validation Errors
51 | return api_response()
52 | ->error()
53 | ->code(422)
54 | ->message('Validation Error')
55 | ->validationErrors($errors)
56 | ->send();
57 |
58 | // With Pagination
59 | return api_response()
60 | ->success()
61 | ->send(User::paginate(10));
62 | ```
63 |
64 | ### Response Format
65 |
66 | ```json
67 | {
68 | "status": {
69 | "code": 200,
70 | "message": "Welcome!",
71 | "error": false,
72 | "validation_errors": []
73 | },
74 | "data": {
75 | "name": "Laravel"
76 | }
77 | }
78 | ```
79 |
80 | ## Documentation
81 |
82 | ### Configuration
83 |
84 | Publish the config file:
85 | ```bash
86 | php artisan vendor:publish --tag=api-response-config
87 | ```
88 |
89 | Customize response keys, messages, and more in `config/api-response.php`:
90 |
91 | ```php
92 | return [
93 | 'keys' => [
94 | 'status' => 'status',
95 | 'code' => 'code',
96 | // ... customize your keys
97 | ],
98 | 'logging' => [
99 | 'enabled' => env('API_RESPONSE_LOGGING', false),
100 | ],
101 | 'error_messages' => [
102 | 200 => 'Success',
103 | 404 => 'Resource Not Found',
104 | // ... customize your messages
105 | ],
106 | ];
107 | ```
108 |
109 | ### Exception Handling
110 |
111 | Add the trait to your controllers:
112 |
113 | ```php
114 | use DarshPhpDev\LaravelApiResponseFormatter\Traits\HandlesApiExceptions;
115 |
116 | class UserController extends Controller
117 | {
118 | use HandlesApiExceptions;
119 |
120 | public function show($id)
121 | {
122 | try {
123 | $user = User::findOrFail($id);
124 | return api_response()
125 | ->success()
126 | ->send($user);
127 | } catch (\Throwable $e) {
128 | return $this->handleApiException($e);
129 | }
130 | }
131 | }
132 | ```
133 |
134 | ## Advanced Usage
135 |
136 | ### Method Chaining
137 |
138 | ```php
139 | return api_response()
140 | ->success()
141 | ->message('Created successfully')
142 | ->code(201)
143 | ->headers(['X-Custom-Header' => 'Value'])
144 | ->send($data);
145 | ```
146 |
147 | ### Pagination Support
148 |
149 | ```php
150 | $users = User::paginate(10);
151 |
152 | return api_response()
153 | ->success()
154 | ->message('Users retrieved')
155 | ->send($users);
156 | ```
157 |
158 | Response includes pagination metadata:
159 | ```json
160 | {
161 | "status": { ... },
162 | "data": {
163 | "items": [...],
164 | "pagination": {
165 | "total": 100,
166 | "per_page": 10,
167 | "current_page": 1,
168 | "last_page": 10
169 | }
170 | }
171 | }
172 | ```
173 |
174 | ## Testing
175 |
176 | ```bash
177 | composer test
178 | ```
179 |
180 | ## Compatibility
181 |
182 | - PHP 7.4+
183 | - Laravel 5.x and above
184 | - PHPUnit 9.x for testing
185 |
186 | ## Contributing
187 |
188 | Contributions are welcome!
189 |
190 | ## Security
191 |
192 | If you discover any security-related issues, please email [mustafa.softcode@gmail.com] instead of using the issue tracker.
193 |
194 | ## Credits
195 |
196 | - [MUSTAFA AHMED](https://github.com/DarshPhpDev)
197 | - [All Contributors](../../contributors)
198 |
199 | ## License
200 |
201 | This package is open-source software licensed under the [MIT License](https://opensource.org/licenses/MIT).
--------------------------------------------------------------------------------
/art/socialcard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DarshPhpDev/laravel-api-response-formatter/f055d3ff60328c47e926fd3185b8789808f95117/art/socialcard.png
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "darshphpdev/laravel-api-response-formatter",
3 | "description": "A Laravel package for standardized API responses",
4 | "type": "library",
5 | "license": "MIT",
6 | "version": "1.1.0",
7 | "autoload": {
8 | "psr-4": {
9 | "DarshPhpDev\\LaravelApiResponseFormatter\\": "src/"
10 | },
11 | "files": [
12 | "src/helpers.php"
13 | ]
14 | },
15 | "authors": [
16 | {
17 | "name": "Mustafa Ahmed",
18 | "email": "mustafa.softcode@gmail.com"
19 | }
20 | ],
21 | "extra": {
22 | "laravel": {
23 | "providers": [
24 | "DarshPhpDev\\LaravelApiResponseFormatter\\ApiResponseServiceProvider"
25 | ]
26 | }
27 | },
28 | "require-dev": {
29 | "phpunit/phpunit": "^9.6",
30 | "orchestra/testbench": "^6.47"
31 | },
32 | "scripts": {
33 | "test": "phpunit"
34 | }
35 | }
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | ./tests
8 |
9 |
10 |
11 |
12 | ./src
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/ApiResponse.php:
--------------------------------------------------------------------------------
1 | config = config('api-response', []);
29 | $this->keys = $this->config['keys'] ?? [];
30 | }
31 |
32 | /**
33 | * Get the error message for a given status code.
34 | *
35 | * @param int $code
36 | * @return string
37 | */
38 | private function getErrorMessage(int $code): string
39 | {
40 | return $this->config['error_messages'][$code] ?? 'Unknown Error';
41 | }
42 |
43 | /**
44 | * Set the response data.
45 | *
46 | * @param mixed $data
47 | * @return $this
48 | */
49 | public function data(mixed $data = null): self
50 | {
51 | $this->data = $data;
52 | return $this;
53 | }
54 |
55 | /**
56 | * Set the response code.
57 | *
58 | * @param int $code
59 | * @return $this
60 | */
61 | public function code(int $code = 200): self
62 | {
63 | $this->code = $code;
64 | return $this;
65 | }
66 |
67 | /**
68 | * Set the response message.
69 | *
70 | * @param string $message
71 | * @return $this
72 | */
73 | public function message(?string $message = null): self
74 | {
75 | $this->message = $message;
76 | return $this;
77 | }
78 |
79 | /**
80 | * Mark the response as an error.
81 | *
82 | * @return $this
83 | */
84 | public function error(): self
85 | {
86 | $this->error = true;
87 | $this->code = $this->code === 200 ? 500 : $this->code;
88 | return $this;
89 | }
90 |
91 | /**
92 | * Mark the response as a success.
93 | *
94 | * @return $this
95 | */
96 | public function success(): self
97 | {
98 | $this->error = false;
99 | return $this;
100 | }
101 |
102 | /**
103 | * Set validation errors.
104 | *
105 | * @param array $validationErrors
106 | * @return $this
107 | */
108 | public function validationErrors(array $validationErrors = []): self
109 | {
110 | $this->validationErrors = $validationErrors;
111 | return $this;
112 | }
113 |
114 | /**
115 | * Set custom headers.
116 | *
117 | * @param array $headers
118 | * @return $this
119 | */
120 | public function headers(array $headers = []): self
121 | {
122 | $this->headers = $headers;
123 | return $this;
124 | }
125 |
126 | /**
127 | * Send the response.
128 | * @param mixed $data
129 | * @return JsonResponse
130 | */
131 | public function send(mixed $data = null): JsonResponse
132 | {
133 | if (func_num_args() > 0) {
134 | $this->data = $data;
135 | }
136 |
137 | $this->message ??= $this->getErrorMessage($this->code);
138 |
139 | // Format paginated data
140 | if ($this->data instanceof AbstractPaginator) {
141 | $this->data = $this->formatPaginatedData($this->data);
142 | }
143 |
144 | // Build the response structure
145 | $response = [
146 | $this->keys['status'] => [
147 | $this->keys['code'] => $this->code,
148 | $this->keys['message'] => $this->message,
149 | $this->keys['error'] => $this->error,
150 | $this->keys['validation_errors'] => $this->validationErrors,
151 | ],
152 | $this->keys['data'] => $this->data,
153 | ];
154 |
155 | // Log the response if enabled
156 | if ($this->config['logging']['enabled'] ?? false) {
157 | logger()->info('API Response:', $response);
158 | }
159 |
160 | return response()->json(
161 | $response,
162 | $this->code,
163 | $this->headers,
164 | JSON_UNESCAPED_UNICODE
165 | );
166 | }
167 |
168 | /**
169 | * Format paginated data.
170 | *
171 | * @param AbstractPaginator $paginator
172 | * @return array
173 | */
174 | private function formatPaginatedData(AbstractPaginator $paginator): array
175 | {
176 | return [
177 | 'items' => $paginator->items(),
178 | 'pagination' => [
179 | 'total' => $paginator->total(),
180 | 'per_page' => $paginator->perPage(),
181 | 'current_page' => $paginator->currentPage(),
182 | 'last_page' => $paginator->lastPage(),
183 | ],
184 | ];
185 | }
186 | }
--------------------------------------------------------------------------------
/src/ApiResponseServiceProvider.php:
--------------------------------------------------------------------------------
1 | mergeConfigFrom(self::CONFIG_PATH, 'api-response');
16 | }
17 |
18 | public function boot(): void
19 | {
20 | // Publish configuration file
21 | if ($this->app->runningInConsole()) {
22 | $this->publishes([
23 | self::CONFIG_PATH => config_path('api-response.php'),
24 | ], 'api-response-config');
25 | }
26 |
27 | // Load helper file
28 | require_once __DIR__ . '/helpers.php';
29 | }
30 | }
--------------------------------------------------------------------------------
/src/Config/api-response.php:
--------------------------------------------------------------------------------
1 | [
13 | 'status' => 'status',
14 | 'code' => 'code',
15 | 'message' => 'message',
16 | 'error' => 'error',
17 | 'validation_errors' => 'validation_errors',
18 | 'data' => 'data',
19 | ],
20 |
21 |
22 |
23 | /*
24 | |--------------------------------------------------------------------------
25 | | Enable logging.
26 | |--------------------------------------------------------------------------
27 | | Set as true if you want to log all api responses, default is false
28 | */
29 |
30 | 'logging' => [
31 | 'enabled' => env('API_RESPONSE_LOGGING', false),
32 | ],
33 |
34 |
35 |
36 | /*
37 | |--------------------------------------------------------------------------
38 | | customize default status codes.
39 | |--------------------------------------------------------------------------
40 | | Here you can customize your default status codes and their corresponding messages
41 | */
42 |
43 | 'error_messages' => [
44 | 200 => 'Success',
45 | 201 => 'Created',
46 | 204 => 'No Content',
47 | 400 => 'Bad Request',
48 | 401 => 'Unauthorized Access',
49 | 403 => 'Forbidden',
50 | 404 => 'Resource Not Found',
51 | 405 => 'Method Not Allowed',
52 | 429 => 'Too Many Requests',
53 | 500 => 'Internal Server Error',
54 | 502 => 'Bad Gateway',
55 | 503 => 'Service Unavailable',
56 | 504 => 'Gateway Timeout',
57 | ],
58 | ];
--------------------------------------------------------------------------------
/src/Traits/HandlesApiExceptions.php:
--------------------------------------------------------------------------------
1 | exceptionHandlers = [
24 | ValidationException::class => fn(ValidationException $e): JsonResponse =>
25 | api_response()
26 | ->error()
27 | ->code(422)
28 | ->message('Validation Error')
29 | ->validationErrors($e->errors())
30 | ->send(),
31 |
32 | ModelNotFoundException::class => fn(ModelNotFoundException $e): JsonResponse =>
33 | api_response()
34 | ->error()
35 | ->code(404)
36 | ->message('Resource Not Found')
37 | ->send(),
38 |
39 | HttpException::class => fn(HttpException $e): JsonResponse =>
40 | api_response()
41 | ->error()
42 | ->code($e->getStatusCode())
43 | ->message($e->getMessage())
44 | ->send(),
45 | ];
46 | }
47 |
48 | /**
49 | * Handle exceptions and return a formatted API response.
50 | */
51 | protected function handleApiException(Throwable $e): JsonResponse
52 | {
53 | if (empty($this->exceptionHandlers)) {
54 | $this->initializeExceptionHandlers();
55 | }
56 |
57 | // Find and execute the handler for the exception
58 | foreach ($this->exceptionHandlers as $exceptionType => $handler) {
59 | if ($e instanceof $exceptionType) {
60 | return $handler($e);
61 | }
62 | }
63 |
64 | // Default handler for uncaught exceptions
65 | return api_response()
66 | ->error()
67 | ->code(500)
68 | ->message('Something went wrong')
69 | ->send();
70 | }
71 | }
--------------------------------------------------------------------------------
/src/helpers.php:
--------------------------------------------------------------------------------
1 | [
13 | 'status' => 'status',
14 | 'code' => 'code',
15 | 'message' => 'message',
16 | 'error' => 'error',
17 | 'validation_errors' => 'validation_errors',
18 | 'data' => 'data',
19 | ],
20 | 'logging' => [
21 | 'enabled' => false,
22 | ],
23 | 'error_messages' => [
24 | 200 => 'Success',
25 | 400 => 'Bad Request',
26 | 401 => 'Unauthorized Access',
27 | 403 => 'Forbidden',
28 | 404 => 'Resource Not Found',
29 | 500 => 'Internal Server Error',
30 | ],
31 | ];
32 |
33 | protected function setUp(): void
34 | {
35 | parent::setUp();
36 | }
37 |
38 | protected function getPackageProviders($app): array
39 | {
40 | return [
41 | \DarshPhpDev\LaravelApiResponseFormatter\ApiResponseServiceProvider::class,
42 | ];
43 | }
44 |
45 | protected function getEnvironmentSetUp($app): void
46 | {
47 | $app['config']->set('api-response', $this->defaultConfig);
48 | }
49 |
50 | /** @test */
51 | public function it_creates_a_success_response()
52 | {
53 | $expectedData = [
54 | 'status' => [
55 | 'code' => 200,
56 | 'message' => 'Welcome!',
57 | 'error' => false,
58 | 'validation_errors' => [],
59 | ],
60 | 'data' => ['name' => 'Laravel'],
61 | ];
62 |
63 | $response = (new ApiResponse())
64 | ->success()
65 | ->message('Welcome!')
66 | ->data(['name' => 'Laravel'])
67 | ->send();
68 |
69 | $this->assertEquals(200, $response->getStatusCode());
70 | $this->assertJson($response->getContent());
71 | $this->assertJsonStringEqualsJsonString(
72 | json_encode($expectedData),
73 | $response->getContent()
74 | );
75 | }
76 |
77 | /** @test */
78 | public function it_creates_an_error_response(): void
79 | {
80 | $expectedData = [
81 | 'status' => [
82 | 'code' => 404,
83 | 'message' => 'Resource Not Found',
84 | 'error' => true,
85 | 'validation_errors' => [],
86 | ],
87 | 'data' => null,
88 | ];
89 |
90 | $response = (new ApiResponse())
91 | ->error()
92 | ->code(404)
93 | ->message('Resource Not Found')
94 | ->send();
95 |
96 | $this->assertEquals(404, $response->getStatusCode());
97 | $this->assertJson($response->getContent());
98 | $this->assertJsonStringEqualsJsonString(
99 | json_encode($expectedData),
100 | $response->getContent()
101 | );
102 | }
103 |
104 | /** @test */
105 | public function it_creates_a_paginated_response(): void
106 | {
107 | $paginator = new LengthAwarePaginator(
108 | ['item1', 'item2'],
109 | 2,
110 | 10,
111 | 1
112 | );
113 |
114 | $expectedData = [
115 | 'status' => [
116 | 'code' => 200,
117 | 'message' => 'Success',
118 | 'error' => false,
119 | 'validation_errors' => [],
120 | ],
121 | 'data' => [
122 | 'items' => ['item1', 'item2'],
123 | 'pagination' => [
124 | 'total' => 2,
125 | 'per_page' => 10,
126 | 'current_page' => 1,
127 | 'last_page' => 1,
128 | ],
129 | ],
130 | ];
131 |
132 | $response = (new ApiResponse())
133 | ->data($paginator)
134 | ->send();
135 |
136 | $this->assertEquals(200, $response->getStatusCode());
137 | $this->assertJson($response->getContent());
138 | $this->assertJsonStringEqualsJsonString(
139 | json_encode($expectedData),
140 | $response->getContent()
141 | );
142 | }
143 |
144 | /** @test */
145 | public function it_creates_a_response_with_validation_errors(): void
146 | {
147 | $expectedData = [
148 | 'status' => [
149 | 'code' => 422,
150 | 'message' => 'Validation Error',
151 | 'error' => true,
152 | 'validation_errors' => [
153 | 'email' => ['The email field is required.'],
154 | ],
155 | ],
156 | 'data' => null,
157 | ];
158 |
159 | $response = (new ApiResponse())
160 | ->error()
161 | ->code(422)
162 | ->message('Validation Error')
163 | ->validationErrors(['email' => ['The email field is required.']])
164 | ->send();
165 |
166 | $this->assertEquals(422, $response->getStatusCode());
167 | $this->assertJson($response->getContent());
168 | $this->assertJsonStringEqualsJsonString(
169 | json_encode($expectedData),
170 | $response->getContent()
171 | );
172 | }
173 |
174 | /** @test */
175 | public function it_creates_a_response_with_custom_headers(): void
176 | {
177 | $response = (new ApiResponse())
178 | ->success()
179 | ->headers(['X-Custom-Header' => 'Value'])
180 | ->send(['name' => 'Laravel']);
181 |
182 | $this->assertEquals(200, $response->getStatusCode());
183 | $this->assertTrue($response->headers->has('X-Custom-Header'));
184 | $this->assertEquals('Value', $response->headers->get('X-Custom-Header'));
185 | }
186 | }
--------------------------------------------------------------------------------
/tests/HandlesApiExceptionsTest.php:
--------------------------------------------------------------------------------
1 | [
16 | 'status' => 'status',
17 | 'code' => 'code',
18 | 'message' => 'message',
19 | 'error' => 'error',
20 | 'validation_errors' => 'validation_errors',
21 | 'data' => 'data',
22 | ],
23 | 'logging' => [
24 | 'enabled' => false,
25 | ],
26 | 'error_messages' => [
27 | 200 => 'Success',
28 | 400 => 'Bad Request',
29 | 401 => 'Unauthorized Access',
30 | 403 => 'Forbidden',
31 | 404 => 'Resource Not Found',
32 | 500 => 'Internal Server Error',
33 | ],
34 | ];
35 |
36 | // Test class using the trait
37 | private $testClass;
38 |
39 | protected function setUp(): void
40 | {
41 | parent::setUp();
42 |
43 | // Create anonymous class with the trait
44 | $this->testClass = new class {
45 | use HandlesApiExceptions;
46 |
47 | public function handle($e)
48 | {
49 | return $this->handleApiException($e);
50 | }
51 | };
52 |
53 | $this->app['config']->set('api-response', $this->defaultConfig);
54 | }
55 |
56 | protected function getPackageProviders($app): array
57 | {
58 | return [
59 | \DarshPhpDev\LaravelApiResponseFormatter\ApiResponseServiceProvider::class,
60 | ];
61 | }
62 |
63 | /** @test */
64 | public function it_handles_validation_exception(): void
65 | {
66 | $validator = Validator::make(
67 | ['email' => 'invalid-email'],
68 | ['email' => 'email']
69 | );
70 |
71 | $exception = new ValidationException($validator);
72 |
73 | $response = $this->testClass->handle($exception);
74 | $content = json_decode($response->getContent(), true);
75 |
76 | $this->assertEquals(422, $response->getStatusCode());
77 | $this->assertEquals('Validation Error', $content['status']['message']);
78 | $this->assertTrue($content['status']['error']);
79 | $this->assertArrayHasKey('email', $content['status']['validation_errors']);
80 | }
81 |
82 | /** @test */
83 | public function it_handles_model_not_found_exception(): void
84 | {
85 | $exception = new ModelNotFoundException();
86 |
87 | $response = $this->testClass->handle($exception);
88 | $content = json_decode($response->getContent(), true);
89 |
90 | $this->assertEquals(404, $response->getStatusCode());
91 | $this->assertEquals('Resource Not Found', $content['status']['message']);
92 | $this->assertTrue($content['status']['error']);
93 | }
94 |
95 | /** @test */
96 | public function it_handles_http_exception(): void
97 | {
98 | $exception = new HttpException(403, 'Forbidden Access');
99 |
100 | $response = $this->testClass->handle($exception);
101 | $content = json_decode($response->getContent(), true);
102 |
103 | $this->assertEquals(403, $response->getStatusCode());
104 | $this->assertEquals('Forbidden Access', $content['status']['message']);
105 | $this->assertTrue($content['status']['error']);
106 | }
107 |
108 | /** @test */
109 | public function it_handles_generic_exception(): void
110 | {
111 | $exception = new \Exception('Unknown error');
112 |
113 | $response = $this->testClass->handle($exception);
114 | $content = json_decode($response->getContent(), true);
115 |
116 | $this->assertEquals(500, $response->getStatusCode());
117 | $this->assertEquals('Something went wrong', $content['status']['message']);
118 | $this->assertTrue($content['status']['error']);
119 | }
120 | }
--------------------------------------------------------------------------------
/tests/HelpersTest.php:
--------------------------------------------------------------------------------
1 | [
11 | 'status' => 'status',
12 | 'code' => 'code',
13 | 'message' => 'message',
14 | 'error' => 'error',
15 | 'validation_errors' => 'validation_errors',
16 | 'data' => 'data',
17 | ],
18 | 'logging' => [
19 | 'enabled' => false,
20 | ],
21 | 'error_messages' => [
22 | 200 => 'Success',
23 | 400 => 'Bad Request',
24 | 401 => 'Unauthorized Access',
25 | 403 => 'Forbidden',
26 | 404 => 'Resource Not Found',
27 | 500 => 'Internal Server Error',
28 | ],
29 | ];
30 |
31 | protected function setUp(): void
32 | {
33 | parent::setUp();
34 | }
35 |
36 | protected function getPackageProviders($app): array
37 | {
38 | return [
39 | \DarshPhpDev\LaravelApiResponseFormatter\ApiResponseServiceProvider::class,
40 | ];
41 | }
42 |
43 | protected function getEnvironmentSetUp($app): void
44 | {
45 | $app['config']->set('api-response', $this->defaultConfig);
46 | }
47 |
48 | /** @test */
49 | public function it_creates_a_success_response_using_helper(): void
50 | {
51 | $expectedData = [
52 | 'status' => [
53 | 'code' => 200,
54 | 'message' => 'Welcome!',
55 | 'error' => false,
56 | 'validation_errors' => [],
57 | ],
58 | 'data' => ['name' => 'Laravel'],
59 | ];
60 |
61 | $response = api_response()
62 | ->success()
63 | ->message('Welcome!')
64 | ->data(['name' => 'Laravel'])
65 | ->send();
66 |
67 | $this->assertEquals(200, $response->getStatusCode());
68 | $this->assertJson($response->getContent());
69 | $this->assertJsonStringEqualsJsonString(
70 | json_encode($expectedData),
71 | $response->getContent()
72 | );
73 | }
74 |
75 | // Add other test methods here...
76 | }
--------------------------------------------------------------------------------