Throttling Submission Of Form In Laravel Example

Sometimes we need to restrict a user from submitting a form within a certain time limit that is to prevent spamming users. Do you know that we can handle it by using throttling. Think you want to restrict a user to submit a form only once in a timeframe of five minutes, now what you do? 

This could be a public message board. If he/she tries to submit the form again in the next five minutes, they won’t be able to. How would you do that? To do that, we can create a new rule called ThrottleSubmission using the following command like so.

Now let's check out laravel custom rules throttle

php artisan make:rule ThrottleSubmission


After runnig the command it will create a new class called ThrottleSubmission in the app/Rules directory. Here’s in the passes() method, you can write the logic that will check if the user is submitting the form in 5 minutes multiple times like so.


namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\User;

class ThrottleSubmission implements Rule
    protected $user;

    public function __construct(User $user)
        $this->user = $user;

     * Determine if the validation rule passes.
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
    public function passes($attribute, $value)
        return $this->user->latestMessage != null ? $this->user->latestMessage->created_at->lt(
        ): null;

     * Get the validation error message.
     * @return string
    public function message()
        return 'Try submitting after some time.';


Well, now Once done, you can attach this rule to a validator by passing an instance of the rule object with your other validation rules on the input field like so.

use App\Rules\ThrottleSubmission;

    'message' => [
        new ThrottleSubmission


Read also : How to Set Limit Login Attempts in Laravel 7


Hope it can help you.


#laravel #throttling #laravel-8x #limit-attempts