Laravel - 限制用户发帖数量

Laravel - limiting users for number of posts

有什么方法可以限制我项目中用户的帖子数量。例如,我希望我的用户每人最多可以创建 10 个帖子。那么一个用户有 10 个帖子?是 hasMany 还是其他什么东西?请帮助找到解决方案。谢谢

if ($user->posts->count() >= 10) {
  //
}

根据定义

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

要防止用户添加超过 10 个帖子,您需要创建一个中间件来保护您的 posts/create 路由

要创建新的中间件,请使用 make:middleware Artisan 命令:

php artisan make:middleware CheckUserPostsNumber

此命令将在您的 app/Http/Middleware 目录中放置一个新的 CheckUserPostsNumber class。在此中间件中,如果用户发布的号码小于 10,我们将仅允许访问 posts/create 路由。否则,您会将用户重定向回主 URI:

<?php

namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;

class CheckUserPostsNumber
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::user()->posts->count() >= 10) {
            return redirect('home');
        }

        return $next($request);
    }
}

正在为路由分配中间件

您想将中间件分配给特定的路由,您应该首先在 app/Http/Kernel.php 文件中为中间件分配一个键。默认情况下,此 class 的 $routeMiddleware 属性 包含 Laravel 中包含的中间件的条目。要添加您自己的,请将其附加到此列表并为其分配您选择的密钥:

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    //...
    'checkUserPostsNumber' => 'App\Http\Middleware\checkUserPostsNumber'
];

一旦在 HTTP 内核中定义了中间件,您就可以使用 middleware 方法将中间件分配给路由:

Route::get('posts/create', function () {
    //
})->middleware('auth', 'checkUserPostsNumber');

Docs