Nishantha Kumara
Nishantha Kumara

Reputation: 435

Add status flag to Laravel validation response

How can I add the status flag to Laravel (6.0) validation response? this is my validation class.

class LoginRequest extends FormRequest{

public function authorize()
{
    return true;
}


public function rules()
{
    return [
        'email' => 'required|email|exists:users,email',
        'password' => 'required|min:4|max:8'
    ];
 }
}

according to the above validation following response is a return

{
"message": "The given data was invalid.",
"errors": {
    "email": [
        "The selected email is invalid."
    ]
 }
}

but I need reformat above response like this.

{
"status": "fail",
"message": "The given data was invalid.",
"errors": {
    "email": [
        "The selected email is invalid."
    ]
 }
}

Upvotes: 1

Views: 1141

Answers (2)

linktoahref
linktoahref

Reputation: 7992

Create a custom exception.

php artisan make:exception MyCustomException

Then, override the failedValidation method from FormRequest class

use Illuminate\Contracts\Validation\Validator;
use App\Exceptions\MyCustomException;

class LoginRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:4|max:8'
        ];
    }

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     *
     * @return void
     *
     * @throws \App\Exceptions\MyCustomException
     */
    protected function failedValidation(Validator $validator)
    {
        throw (new MyCustomException($validator));
    }
}

and handle the response in App\Exceptions\MyCustomException class

<?php

namespace App\Exceptions;

use Exception;
use Symfony\Component\HttpFoundation\Response;

class MyCustomException extends Exception
{
    /**
     * The validator instance.
     *
     * @var \Illuminate\Contracts\Validation\Validator
     */
    public $validator;

    /**
     * Create a new exception instance.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     */
    public function __construct($validator)
    {
        parent::__construct('The given data was invalid.');

        $this->validator = $validator;
    }

    /**
     * Get all of the validation error messages.
     *
     * @return array
     */
    public function errors()
    {
        return $this->validator->errors()->messages();
    }

    /**
     * Report the exception.
     *
     * @return void
     */
    public function report()
    {
        //
    }

    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        if ($request->acceptsJson()) {
            $errors = [
                'status' => false,
                'message' => 'The given data was invalid',
                'errors' => $this->errors(),
            ];

            return response()->json($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
        }
    }
}

Upvotes: 1

Omer YILMAZ
Omer YILMAZ

Reputation: 1263

All you need, create your response method and override failedValidation. Clear?

Update

In LoginRequest

protected function failedValidation(Validator $validator)
{
    $this->currentValidator = $validator;

    throw new ValidationException($validator, $this->errorResponse(
        $this->formatErrors($validator)
    ));
}

protected function errorResponse(array $errors)
{
    //something else
    return response($errors);
}

Please look up Illuminate\Validation\ValidationException

Upvotes: 1

Related Questions