6

I'm using ThrottleRequest to throttle login attempts. In Kendler.php i have

'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

and my route in web.php

Route::post('login', ['middleware' => 'throttle:3,1', 'uses' => 'Auth\LoginController@authenticate']);

When i login fourth time, it return status 429 with message 'TOO MANY REQUESTS.' (by default i guess)
But i just want to return error message, somethings like:

return redirect('/login')
            ->withErrors(['errors' => 'xxxxxxx']);

Anybody help me! THANK YOU!

hayumi kuran
  • 391
  • 9
  • 21

2 Answers2

10

You can either extend the middleware and override the buildException() method to change the message it passes when it throws a ThrottleRequestsException or you can use your exception handler to catch the ThrottleRequestsException and do whatever you want.

so in Exceptions/Handler.php you could do something like

use Illuminate\Http\Exceptions\ThrottleRequestsException;

public function render($request, Exception $exception)
{
    if ($exception instanceof ThrottleRequestsException) {
      //Do whatever you want here.
    }

    return parent::render($request, $exception);
}
Joe
  • 4,618
  • 3
  • 28
  • 35
0

Or since Laravel 8 you can do it in the new style:

Renderable in the register method in app\exceptions\Handler.php

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;

class Handler extends ExceptionHandler
 
/**
 * Register the exception handling callbacks for the application.
 */
public function register(): void
{
    // Create a renderable
    // see https://laravel.com/docs/10.x/errors#rendering-exceptions
    $this->renderable(function (ThrottleRequestsException $e) {
        return redirect('/login')
            ->withErrors(['errors' => 'xxxxxxx']);
    });
}
Alexander Taubenkorb
  • 3,031
  • 2
  • 28
  • 30