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',
];
}
}
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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With