Search code examples
laravelpostmaxlimit

Laravel - limiting users for number of posts


Is there any way to limit users in my project for number of posts. For example, I want my users can create a maximum 10 posts each one. So one user has 10 posts? Is it something with hasMany or something else? Please help find a solution. Thank you


Solution

  • By definition

    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.

    To prevent user from adding more than 10 posts you need to create a middleware to protect your posts/create route

    To create a new middleware, use the make:middleware Artisan command:

    php artisan make:middleware CheckUserPostsNumber
    

    This command will place a new CheckUserPostsNumber class within your app/Http/Middleware directory. In this middleware, we will only allow access to the posts/create route if the user posts number < than 10. Otherwise, you will redirect the user back to the home 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);
        }
    }
    

    Assigning Middleware To Routes

    you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, append it to this list and assign it a key of your choosing:

    // 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'
    ];
    

    Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:

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

    Docs