节流评论

Throttling comments

我想做到这样,用户每分钟最多只能 post 1 条评论。

我试过只使用 throttle 中间件,但它不起作用。我仍然可以每秒 post 评论。

路线代码:

Route::post('comment/{id}', 'HomeController@comment')->name('comment')->middleware('throttle');

控制器代码:

public function comment($id)
{
    $this->validate(request(), [
        "body" => "required",
    ]);

    $jersey = Jersey::findOrFail($id);
    $comment = new Comment;
    $comment->user_id = auth()->user()->id;
    $comment->jersey_id = $jersey->id;
    $comment->body = request()->input('body');
    $comment->save();
    activity()->by(auth()->user())->withProperties($comment)->log('Commented');
    request()->session()->flash('status', 'Comment submitted!');

    return redirect()->route('concept', $id);
}

如果用户试图每分钟 post 超过 1 条评论,我该如何做到它会闪烁错误而不是保存?

通常我在这样的路线组中使用油门:

Route::group(['middleware' => 'throttle:1'], function () {
    // Your routes here
    Route::get('/', 'HomeController@comment')->name('comment');
    // ...
)}

但在您的情况下,您可以通过指定节流参数来修改代码:

Route::post('comment/{id}', 'HomeController@comment')->name('comment')->middleware('throttle:1');

不要忘记清除缓存以应用更改。

我最终使用了 https://github.com/GrahamCampbell/Laravel-Throttle 包。