Valter Sousa Cardoso
Valter Sousa Cardoso

Reputation: 543

Anti spam system laravel

I want to prevent users from spamming comments on my site, so I make this before insert, in controller:

public function link_comment($id) {
    $spam_checker = DB::table('comments')
    ->whereDate('created_at', today())
    ->where('user_id', auth()->user()->id)
    ->orderby('id', 'desc')
    ->take(5)
    ->get();
}

So, I want to check if the user send 5 comments within 1 minute, if so send a error. How can I make it?

Obs: the date is timestamps.

Upvotes: 0

Views: 727

Answers (2)

arun
arun

Reputation: 4815

At the top of controller use Carbon\Carbon;

  public function link_comment($id) {
        $spam_checker = DB::table('comments')
        ->whereBetween('created_at', [Carbon::now()->subMinutes(1)->toDateTimeString(), Carbon::now()])
        ->where('user_id', auth()->user()->id)
        ->orderby('id', 'desc')
            ->get();
       if(count($spam_checker)>=5){
         //send a error here.
       }
    }

Upvotes: 1

user320487
user320487

Reputation:

Laravel offers a middleware for this called ThrottleRequests.

You can set restrictions based on the number of requests made within a time interval.

Upvotes: 1

Related Questions