Skip to content

Instantly share code, notes, and snippets.

@xmhafiz
Last active November 8, 2017 14:40
Show Gist options
  • Save xmhafiz/cf7a7952562f08f518965ae119f15441 to your computer and use it in GitHub Desktop.
Save xmhafiz/cf7a7952562f08f518965ae119f15441 to your computer and use it in GitHub Desktop.
Laravel 5.4 - Custom default validation error output and status code to 400

What's the problem?

In laravel 5.4, when using $this->validate() function, it will give the default errors format with 422 status code as below.

{
  "username": [
    "The username field is required."
  ],
  "email": [
    "The email field is required."
  ],
  "fullname": [
    "The fullname field is required."
  ]
}

So how?

As refer to docs and this post, I try to come with solution on override App\Http\Controllers\Controller on two methods as to get the below output with 400 status code.

[
  "The username field is required.",
  "The email field is required.",
  "The fullname field is required."
]
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Validation\Validator;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
// custom error message display
protected function formatValidationErrors(Validator $validator)
{
return $validator->errors()->all();
}
// custom validation error status code to 400 (instead of 422)
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 400);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment