N
N
nikilex2020-09-09 20:05:14
Laravel
nikilex, 2020-09-09 20:05:14

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,
        ];
    }
}

The Requests file with validation rules and the withValidator method, which customizes my errors, but if the validation is successful, it outputs JSON with the same fields that I'm trying to customize, but empty, but I would like to execute the code in the controller and add data to the database.
<?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);
        });
    }
}

Controller file
<?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);
    }
}

Handler.php file

<?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
Route::apiResources([
    '/tasks'    => 'TaskController',
]);

What other methods can be used to customize validation errors?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex Wells, 2020-09-09
@Alex_Wells

It is possible, but not necessary. The task of the frontend, solve it there.

S
Stalker_RED, 2015-09-09
@DarCKoder

You can change not the div, but only the address of the video jsfiddle.net/wfxwvtLb

M
Maxim Timofeev, 2015-09-09
@webinar

Use simple ajax

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question