如何为每个用户插入数量有限的记录?

时间:2019-07-14 09:24:08

标签: laravel laravel-5 laravel-5.4

我有视频网站。我想限制用户,以便每个用户可以发布10个帖子。

我尝试搜索插入查询,以此限制每个用户的插入。

我希望每个用户只能发布10条帖子。

1 个答案:

答案 0 :(得分:0)

在模型Post.php中,添加以下内容:

protected static $maxPostsAllowedPerUser = 10;

public static function guardAgainstMaxPosts()
{
    return true == self::where('user_id', auth()->user()->id)->count() < self::$maxPostsAllowedPerUser;
}

然后在控制器中:

if(!Post::guardAgainstMaxPosts())
{
   // max entries reached
   // throw exception
}

// continue with the normal code here

希望有帮助!