Laravel FormRequest Custom Validation Response

Are you building a restAPI and wanted to utilize laravel’s FormRequest validation, however, having a hard time how to customize the response of it? Actually, you’ll be surprised how easy it was, just like me or maybe not LOL!

Anyway, here's how to customize the response of laravel’s FormRequest.

Here in our example we will be building a login/authentication restAPI so we will begin creating the files we’re about to modify. Please note that our example focus mainly on how to override the response of formrequest and is not a fully functional login api.

LoginController
php artisan make:controller LoginController

LoginRequest
php artisan make:request LoginRequest

Now let’s begin with LoginController.php located at app\Http\Controllers and replace the code using below.

<?php 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Requests\LoginRequest;
class LoginController extends BaseController
{
public function postLogin(LoginRequest $request) {
return [
'status' => true,
'message' => 'Successfully logged in!'
];
}
}
?>

Next is LoginRequest.php located at app\Http\Requests and use the code below.

<?php 
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Validation\Factory as ValidationFactory;
class LoginRequest extends FormRequest
{
protected function failedValidation(Validator $validator) {
throw new HttpResponseException(
response()->json([
'status' => false,
'messages' => $validator->errors()->all()
], 200)
);
}
public function authorize()
{
return true;
}
public function rules()
{
return [
'username' => 'required',
'password' => 'required'
];
}
}
?>

The last part is add it to our route located at routes/web.php for new version of laravel app/Http/routes.php for older version.

Route::post('login', '[email protected]');

 

And if you encounter an error while testing the login probably it's the csrf middleware laravel that causing it, just disable it by updating the file app/Http/Kernel.php by removing the code below.

\App\Http\Middleware\VerifyCsrfToken::class,

 

Here's the example result of what I did in postman by sending to the url without the username and password.

 

Happy coding!