Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 change form request failed validation behavior

I have a form request to validate registration data. The application is a mobile API and I would like this class to return formatted JSON in case of a failed validation instead of what it does by default (redirection).

I tried overriding the method failedValidation from Illuminate\Foundation\Http\FormRequest class. but that doesn't seem to work. Any ideas?

Code:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Contracts\Validation\Validator;

class RegisterFormRequest extends Request {

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize() {
    return TRUE;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules() {
    return [
        'email' => 'email|required|unique:users',
        'password' => 'required|min:6',
    ];
}

}
like image 979
Khalid Dabjan Avatar asked May 29 '15 11:05

Khalid Dabjan


2 Answers

No need override any function. just you add the

Accept: application/json

In your form header. Laravel will return the response in same URL and in JSON format.

like image 175
Balachandiran Avatar answered Sep 28 '22 08:09

Balachandiran


By looking at following function in Illuminate\Foundation\Http\FormRequest, it seems Laravel handles it properly.

    /**
     * Get the proper failed validation response for the request.
     *
     * @param  array  $errors
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function response(array $errors)
    {
        if ($this->ajax() || $this->wantsJson())
        {
            return new JsonResponse($errors, 422);
        }

        return $this->redirector->to($this->getRedirectUrl())
                                        ->withInput($this->except($this->dontFlash))
                                        ->withErrors($errors, $this->errorBag);
    }

And as per wantsJson function in Illuminate\Http\Request below, you must explicitly seek JSON response,

    /**
     * Determine if the current request is asking for JSON in return.
     *
     * @return bool
     */
    public function wantsJson()
    {
        $acceptable = $this->getAcceptableContentTypes();

        return isset($acceptable[0]) && $acceptable[0] == 'application/json';
    }
like image 42
pinkal vansia Avatar answered Sep 28 '22 07:09

pinkal vansia