Usermanager/Http/Requests/Role/UpdateRoleRequest.php

66 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2023-05-16 09:57:59 +00:00
<?php
2023-05-20 14:10:32 +00:00
namespace Modules\Usermanager\Http\Requests\Role;
2023-05-16 09:57:59 +00:00
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;
class UpdateRoleRequest 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 [
2023-05-21 05:37:35 +00:00
'name' => 'required|max:100|unique:roles,name,' . $this->role->id,
2023-05-16 09:57:59 +00:00
'guard_name' => 'nullable|max:100|string'
];
}
/**
* Configure the validator instance.
*/
public function withValidator(Validator $validator)
: void
{
$validator->after(function (Validator $validator) {
if ($validator->errors()->any()) {
$error = json_decode($validator->errors()->toJson(), true);
foreach ($error as $key => $value) {
flash($value[0]);
}
return redirect()->route('user.roles.index')->with('error', 'Role 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' => 'Role updated failed.'
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}