【问题标题】:Throttling comments限制评论
【发布时间】:2017-12-02 16:14:51
【问题描述】:

我想让用户每分钟最多只能发表 1 条评论。

我尝试过简单地使用 throttle 中间件,但它不起作用。我仍然可以每秒发布 cmets。

路线代码:

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);
}

如果用户每分钟尝试发布超过 1 条评论,我该如何设置它以闪烁错误而不是保存?

【问题讨论】:

  • throttle 中间件是 Laravel 的核心功能。

标签: php laravel throttling


【解决方案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');

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

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2012-09-17
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2013-06-02
      相关资源
      最近更新 更多