Wesley Schravendijk
Wesley Schravendijk

Reputation: 495

Laravel validation with custom json respons

Quick question. Would it be possible to changes the JSON validation response of laravel? This is for a custom API that I am building in Laravel.

Validation process

$validation = $this->validate( 
    $request, [
        'user_id' => 'required', 
    ]);

The response shows up like this in json

{
  "message": "The given data was invalid.",
  "errors": {
    "user_id": [
      "The user id field is required."
    ],
  }
}

Preferable it would become something like this.

{
    "common:" [
        "status": "invalid",
        "message": "Param xxxx is required",
    ],
}

What would be the best way to changes this? Is it even possible?

Thank you.

Upvotes: 9

Views: 5479

Answers (3)

Arsel Muginov
Arsel Muginov

Reputation: 113

I was searching for an answer to this and I think I found a better way. There is an exception handler in a default Laravel app - \App\Exceptions\Handler - and you can override the invalidJson method:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    // ...

    protected function invalidJson($request, ValidationException $exception)
    {
        $errors = [];
        foreach ($exception->errors() as $field => $messages) {
            foreach ($messages as $message) {
                $errors[] = [
                    'code' => $field,
                    'message' => $message,
                ];
            }
        }
    
        return response()->json([
            'error' => $errors,
        ], $exception->status);
    }
}

Upvotes: 6

Chris
Chris

Reputation: 2035

@Dev Ramesh solution is still perfectly valid for placing inline within your controller.

For those of you looking to abstract this logic out into a FormRequest, FormRequest has a handy override method called failedValidation. When this is hit, you can throw your own response exception, like so...

/**
 * When we fail validation, override our default error.
 *
 * @param ValidatorContract $validator
 */
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $errors = $this->validator->errors();

    throw new \Illuminate\Http\Exceptions\HttpResponseException(
        response()->json([
            'errors' => $errors,
            'message' => 'The given data was invalid.',

            'testing' => 'Whatever custom data you want here...',
        ], 422)
    );
}

Upvotes: 1

Dev Ramesh
Dev Ramesh

Reputation: 363

You can do this, and it will be reflected globally. Navigate to below folder and use Controller.php app/Http/Controllers

use Illuminate\Http\Request;

Write below method in Controller.php and change response as you want.

public function validate(
    Request $request,
    array $rules,
    array $messages = [],
    array $customAttributes = [])
{
    $validator = $this->getValidationFactory()
        ->make(
            $request->all(),
            $rules, $messages,
            $customAttributes
        );
    if ($validator->fails()) {
        $errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
        throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
            [
                'status' => false,
                'message' => "Some fields are missing!",
                'error_code' => 1,
                'errors' => $errors
            ], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
    }
}

I have tried it with Laravel 5.6, maybe this is useful for you.

Upvotes: 5

Related Questions