Cetaklabel/Http/Requests/SpecialCode/StoreSpecialCodeRequest.php

67 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2023-05-15 10:03:46 +00:00
<?php
2023-05-20 14:09:49 +00:00
namespace Modules\Cetaklabel\Http\Requests\SpecialCode;
2023-05-15 10:03:46 +00:00
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;
use Symfony\Component\HttpFoundation\JsonResponse;
class StoreSpecialCodeRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
2023-05-15 14:14:52 +00:00
public function authorize()
: bool
2023-05-15 10:03:46 +00:00
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
*/
2023-05-15 14:14:52 +00:00
public function rules()
: array
2023-05-15 10:03:46 +00:00
{
return [
'kode' => 'required|string|max:2|min:2|unique:special_codes,kode',
'name' => 'required|string|max:50',
'description' => 'nullable|string|max:255'
2023-05-15 10:03:46 +00:00
];
}
/**
* Configure the validator instance.
*/
2023-05-15 14:14:52 +00:00
public function withValidator(Validator $validator)
: void
2023-05-15 10:03:46 +00:00
{
2023-05-15 14:14:52 +00:00
$validator->after(function (Validator $validator) {
if ($validator->errors()->any()) {
$error = json_decode($validator->errors()->toJson(), true);
2023-05-15 10:03:46 +00:00
foreach ($error as $key => $value) {
2023-05-15 14:14:52 +00:00
flash($value[0]);
2023-05-15 10:03:46 +00:00
}
2023-05-15 14:14:52 +00:00
return redirect()->route('special-code.index')->with('error', 'Special Code created failed.');
2023-05-15 10:03:46 +00:00
}
});
}
2023-05-15 14:14:52 +00:00
protected function failedValidation(Validator|\Illuminate\Contracts\Validation\Validator $validator)
: JsonResponse
2023-05-15 10:03:46 +00:00
{
2023-05-15 14:14:52 +00:00
$errors = (new ValidationException($validator))->errors();
2023-05-15 10:03:46 +00:00
2023-05-15 14:14:52 +00:00
throw new HttpResponseException(response()->json([
2023-05-15 10:03:46 +00:00
'success' => false,
'errors' => $errors,
'messages' => 'Special Code created failed.'
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}