Posted by

Laravel FormRequest Custom Validation Response

Laravel's FormRequest validation was very ideal on building a restAPI, as you can customize how or what you wanted it to response.

Here's how you can customize the response of it.

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()
      ], 401)
    ); 
  }
  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', 'LoginController@postLogin');

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!