Laravel Prevent Users from Re-Submitting Form (Throttle Submission)

Hello Artisans, today I'll discuss about how you can prevent a user from submitting a form/ send a message within a certain period of time. Sometimes we face a scenario where we 've to prevent the users for a sometime, so that user can not send the message/ cannot submit a form. Especially to prevent spamming by users. So, let's see how we can prevent the user submitting a form again and again in a certain period of time.

Suppose, there is a public message board, and we want to submit a form by a user once in a five minutes. And if he/she wants to submit the form again in the five minutes, he/she can't able to do it. How will you do it?

For this, we can create our own custom validation rule. We can make it by the below command.

php artisan make:rule ThrottleSubmission

This will create a ThrottleSubmission.php file under app\Rules directory. Open the file and here you can see the passes() method, where we can put our logic and message() method where we can give the message if validation fails. So, our ThrottleSubmission.php file will finally look like below

app/Rules/ThrottleSubmission.php
<?php

namespace App\Rules;

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

class ThrottleSubmission implements Rule
{
    public function passes($attribute, $value): ?bool
    {
        return auth()->user()->latestMessage != null ? auth()->user()->latestMessage->created_at->lt(
            now()->subMinutes(5)
        ): null;
    }

    public function message(): string
    {
        return 'Try submitting the form after 5 minutes.';
    }
}

And finally in our controller we can call the rule as follows

app/Rules/ThrottleSubmission.php
use App\Rules\ThrottleSubmission;

$request->validate([
            'message' => 'required',new ThrottleSubmission()
        ]);

And this will prevent the user to submit a form multiple times in s span of five minutes.

That's it for today. Hope you'll enjoy this tutorial. Thanks for reading. ๐Ÿ™‚