Skip to content

Instantly share code, notes, and snippets.

@syofyanzuhad
Forked from jamesmills/FormRequest.php
Last active September 12, 2021 20:55
Show Gist options
  • Save syofyanzuhad/3656e265ac22eb67344caa3a7e013671 to your computer and use it in GitHub Desktop.
Save syofyanzuhad/3656e265ac22eb67344caa3a7e013671 to your computer and use it in GitHub Desktop.
change your default extends FormRequest to your customize FormRequest (API ONLY)
<?php
namespace App\Http\Requests\Api;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
abstract class FormRequest extends LaravelFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
abstract public function rules(Request $request);
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
abstract public function authorize();
/**
* Handle a failed validation attempt.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function failedValidation(Validator $validator)
{
$errors = (new ValidationException($validator))->errors();
$transformed = [];
foreach ($errors as $field => $message) {
$transformed[] = [
'field' => $field,
'message' => $message[0]
];
}
throw new HttpResponseException(
response()->json([
'success' => false,
'status' => 'error_validasi',
'message' => 'Terjadi error saat mengirimkan request',
'errors' => $transformed,
'data' => null,
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment