@@ -17,8 +17,8 @@ By default, the stucture of the API response looks like this:
17
17
}
18
18
```
19
19
20
- > ** Note** : For now, if you want to customize the response structure, you need to manually extend ` ApiResponse `
21
- > class and override ` toResponse ` or ` getResponse ` method.
20
+ > ** Note** : For now, if you want to customize the response structure,
21
+ > you need to manually extend ` ApiResponse ` class and override ` toResponse ` method.
22
22
23
23
## Install
24
24
@@ -70,8 +70,9 @@ ApiResponse::error()
70
70
71
71
### Validate or Fail
72
72
73
- Use this helper to validate user submitted request then return
73
+ Use this helper to validate user submitted request, then return
74
74
an ` ApiResponse::error ` response if the validation fails.
75
+
75
76
With this helper, now you can use something like ` $request->validate() `
76
77
without worrying on how to handle the redirect response or validation errors
77
78
separately.
@@ -93,8 +94,9 @@ if ($validator->fails()) {
93
94
94
95
// with this helper
95
96
96
- // it will automatically return a json response if validation fails
97
- ApiResponse::validateOrFail([
97
+ // it will automatically return a json response if validation fails
98
+ // if the validation passes, it will return validated data
99
+ $validatedData = ApiResponse::validateOrFail([
98
100
'email' => 'required|email',
99
101
'username' => 'required|unique:users,username',
100
102
]);
@@ -103,7 +105,7 @@ ApiResponse::validateOrFail([
103
105
### Throwing an Exception
104
106
105
107
Instead of using ` ApiResponse ` manually, you can also throw an exception
106
- and got the same response according to the exception type.
108
+ and will get the same response according to the exception type.
107
109
108
110
This package provides two exception: ` ApiException ` and ` ApiValidationException ` .
109
111
@@ -120,6 +122,37 @@ if ($user->balance <= 100_000) {
120
122
}
121
123
```
122
124
125
+ ### Handling all Exception
126
+
127
+ If you would like to convert all laravel exception to return an ApiResponse,
128
+ you can use the ` ExceptionHandler::renderAsApiResponse ` helper.
129
+
130
+ ``` php
131
+ // file: Exception/Handler.php
132
+
133
+ use KodePandai\ApiResponse\ExceptionHandler;
134
+
135
+ // new laravel (>= 8)
136
+ public function register()
137
+ {
138
+ $this->renderable(function (Throwable $e, $request) {
139
+ if ($request->wantsJson()) {
140
+ return ExceptionHandler::renderAsApiResponse($e);
141
+ }
142
+ });
143
+ }
144
+
145
+ // old laravel (<= 7)
146
+ public function render($request, Throwable $exception)
147
+ {
148
+ if ($request->wantsJson()) {
149
+ return ExceptionHandler::renderAsApiResponse($exception);
150
+ }
151
+
152
+ return parent::render($request, $exception);
153
+ }
154
+ ```
155
+
123
156
## Develop
124
157
125
- * To test, run ` composer test ` .
158
+ * To test run ` composer test ` .
0 commit comments