Answer the question
In order to leave comments, you need to log in
How to customize laravel 7 validation errors via Requests for API?
Hello, please tell me how to customize validation errors for a response from the API via Requests.
Now I have a Resources file
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Task extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'estimate' => $this->estimate,
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TaskRequest extends FormRequest
{
public function rules()
{
return [
'Title' => 'required|string',
'Description' => 'required|string',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
$fields = [
'Title' => $validator->errors()->first('Title'),
'Description' => $validator->errors()->first('Description')
];
$validator->errors()->add('fields', $fields);
});
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\TaskRequest;
use App\Task;
use App\Http\Resources\Task as TaskResources;
class TaskController extends Controller
{
public function store(TaskRequest $request)
{
$task = Task::create([
'title' => $request->Title,
'description' => $request->Description,
'backlog_id' => 1,
'status' => 'opened',
]);
$json = [
'id' => 'TASK-'.$task->id
];
return response()->json($json, 201);
}
}
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Validation\ValidationException;
class Handler extends ExceptionHandler
{
public function render($request, Throwable $exception)
{
if ($request->ajax() || $request->wantsJson())
{
// если это не ошибка валидации, то пишем сообщение, полученное из экземпляра исключения
$message = [$exception->getMessage()];
// если ошибка валидации
if($exception instanceof ValidationException) {
$message = $exception->errors();
}
$json = [
'Errors' => [
'Fields' => isset($message['fields']) ? $message['fields'] : '',
'Global' => isset($message['global']) ? $message['global'] : ''
],
];
// возвращаем массив ошибок
return response()->json($json, 400);
}
return parent::render($request, $exception);
}
}
Route::apiResources([
'/tasks' => 'TaskController',
]);
Answer the question
In order to leave comments, you need to log in
It is possible, but not necessary. The task of the frontend, solve it there.
You can change not the div, but only the address of the video jsfiddle.net/wfxwvtLb
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question