Master/Http/Requests/SubDistrict/UpdateSubDistrictRequest.php

70 lines
2.3 KiB
PHP
Raw Normal View History

2023-06-04 14:09:39 +00:00
<?php
namespace Modules\Master\Http\Requests\SubDistrict;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;
use Symfony\Component\HttpFoundation\JsonResponse;
class UpdateSubDistrictRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize()
: bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
*/
public function rules()
: array
{
return [
'district_id' => 'required|integer|exists:districts,id',
'code' => 'required|string|max:50|unique:sub_districts,code', $this->sub_district->id,
'name' => 'required|string|max:50|unique:sub_districts,name', $this->sub_district->id,
'postal_code' => 'nullable|integer|min:5|max:5',
'status' => 'nullable|string|max:1',
];
}
/**
* Configure the validator instance.
*/
public function withValidator(Validator $validator)
: void
{
$validator->after(function (Validator $validator) {
if ($validator->errors()->any()) {
$errors = json_decode($validator->errors()->toJson(), true);
foreach ($errors as $key => $value) {
flash($value[0]);
}
return redirect()->route('master.sub-district.index')->with('error', 'Sub District updated failed.');
}
});
}
protected function failedValidation(Validator|\Illuminate\Contracts\Validation\Validator $validator)
: JsonResponse
{
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(response()->json([
'success' => false,
'errors' => $errors,
'messages' => 'Sub District updated failed.'
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}