<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vikash Kumar singh on Medium]]></title>
        <description><![CDATA[Stories by Vikash Kumar singh on Medium]]></description>
        <link>https://medium.com/@vikash.dukeinfo?source=rss-994d55690c46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SyHYbD6suncp7ISZyVLK8g.png</url>
            <title>Stories by Vikash Kumar singh on Medium</title>
            <link>https://medium.com/@vikash.dukeinfo?source=rss-994d55690c46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:07:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikash.dukeinfo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laravel Deployment Guide: From Localhost to Production Server (Complete Step-by-Step Tutorial)]]></title>
            <link>https://medium.com/@vikash.dukeinfo/laravel-deployment-guide-from-localhost-to-production-server-complete-step-by-step-tutorial-c29ab8591372?source=rss-994d55690c46------2</link>
            <guid isPermaLink="false">https://medium.com/p/c29ab8591372</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Vikash Kumar singh]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 12:32:29 GMT</pubDate>
            <atom:updated>2026-11-03T12:32:29.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lITCBmkZE7ztl3_bIC7hmA.png" /><figcaption>Laravel Deployment Guide</figcaption></figure><h3>Learn how to deploy a Laravel application on an Ubuntu VPS using Nginx, PHP-FPM, MySQL, Composer, SSL, queues, cron jobs, and production optimization.</h3><p>Moving a Laravel application from localhost to a live production server is an important skill for every PHP and Laravel developer.</p><p>Developing an application locally using Laravel, MySQL, and PHP is relatively straightforward. However, deploying it to a production environment requires additional knowledge of server configuration, security, database management, file permissions, environment variables, and performance optimization.</p><p>Whether you are a beginner Laravel developer or an experienced PHP developer looking to improve your DevOps skills, understanding the Laravel deployment process is essential.</p><p>In this guide, we’ll walk through the complete process of deploying a Laravel application from a local development environment to a Linux VPS.</p><h3>1. Understanding the Laravel Production Environment</h3><p>Before starting deployment, let’s understand the basic technologies required to run a Laravel application on a production server.</p><p>Our deployment environment will use:</p><ul><li><strong>Operating System:</strong> Ubuntu Linux</li><li><strong>Web Server:</strong> Nginx</li><li><strong>Backend:</strong> PHP with PHP-FPM</li><li><strong>Framework:</strong> Laravel</li><li><strong>Database:</strong> MySQL</li><li><strong>Dependency Manager:</strong> Composer</li><li><strong>Version Control:</strong> Git</li><li><strong>Security:</strong> SSL certificate with HTTPS</li></ul><p>The overall deployment architecture looks like this:</p><pre>User / Browser<br>                    |<br>                    v<br>                HTTPS<br>                    |<br>                    v<br>                Nginx<br>                    |<br>                    v<br>                PHP-FPM<br>                    |<br>                    v<br>             Laravel Application<br>                    |<br>          +---------+---------+<br>          |                   |<br>          v                   v<br>        MySQL             Redis (Optional)<br>          |<br>          v<br>       Database</pre><p>Each component has a specific responsibility.</p><p>Nginx handles incoming HTTP requests, PHP-FPM executes PHP code, Laravel processes application logic, and MySQL stores application data.</p><h3>2. Prepare Your Laravel Application for Deployment</h3><p>Before uploading your Laravel application to a VPS, make sure it works correctly in your local environment.</p><p>First, run your application locally:</p><pre>php artisan serve</pre><p>Check that your application is working correctly.</p><p>Next, install all dependencies:</p><pre>composer install</pre><p>If your project uses frontend assets through Vite, also build them:</p><pre>npm install<br>npm run build</pre><p>Check your Laravel configuration file:</p><pre>.env</pre><p>Your local environment might contain:</p><pre>APP_NAME=MyLaravelApp<br>APP_ENV=local<br>APP_KEY=base64:your_application_key<br>APP_DEBUG=true<br>APP_URL=http://127.0.0.1:8000</pre><p>For production, we’ll update these values on the server.</p><p><strong>Important:</strong> Never upload your local .env file to a public Git repository. It may contain database credentials, API keys, and other sensitive information.</p><p>Also, make sure your Laravel version is compatible with the PHP version installed on your production server. Check your project’s composer.json before selecting a PHP version.</p><h3>3. Connect to Your Ubuntu VPS</h3><p>Once you have a VPS with Ubuntu installed, connect to it using SSH.</p><p>Open your terminal or Windows PowerShell:</p><pre>ssh root@YOUR_SERVER_IP</pre><p>Replace YOUR_SERVER_IP with your actual VPS IP address.</p><p>Update the server packages:</p><pre>sudo apt update<br>sudo apt upgrade -y</pre><p>Install some useful utilities:</p><pre>sudo apt install curl git unzip zip wget software-properties-common -y</pre><p><strong>Security recommendation:</strong> For production servers, create a dedicated non-root deployment user and use SSH key authentication instead of performing everyday deployment operations as root.</p><h3>4. Install Nginx Web Server</h3><p>Nginx is a popular web server used to serve Laravel applications in production.</p><p>Install Nginx:</p><pre>sudo apt install nginx -y</pre><p>Start the Nginx service:</p><pre>sudo systemctl start nginx</pre><p>Enable it to start automatically after a server reboot:</p><pre>sudo systemctl enable nginx</pre><p>Check its status:</p><pre>sudo systemctl status nginx</pre><p>Now open your server IP address in a browser:</p><pre>http://YOUR_SERVER_IP</pre><p>You should see the default Nginx welcome page if everything is configured correctly.</p><h3>5. Install PHP and Required Extensions</h3><p>Laravel requires PHP and several PHP extensions to work correctly.</p><p>The exact PHP version depends on your Laravel version and project dependencies.</p><p>For example, to install PHP 8.3 on a compatible Ubuntu environment:</p><pre>sudo apt install php8.3 php8.3-fpm php8.3-cli php8.3-common \<br>php8.3-mysql php8.3-curl php8.3-mbstring php8.3-xml \<br>php8.3-zip php8.3-bcmath php8.3-gd php8.3-intl -y</pre><p>Install Composer:</p><pre>sudo apt install composer -y</pre><p>Verify PHP:</p><pre>php -v</pre><p>Verify Composer:</p><pre>composer --version</pre><p>Check installed PHP extensions:</p><pre>php -m</pre><p><strong>Developer tip:</strong> PHP CLI and PHP-FPM should use compatible PHP versions and extensions. Otherwise, your application may work through the terminal but fail when accessed through the browser.</p><h3>6. Install MySQL Database Server</h3><p>Laravel applications commonly use MySQL as their database.</p><p>Install MySQL:</p><pre>sudo apt install mysql-server -y</pre><p>Start MySQL:</p><pre>sudo systemctl start mysql</pre><p>Enable it on startup:</p><pre>sudo systemctl enable mysql</pre><p>Run the MySQL security configuration:</p><pre>sudo mysql_secure_installation</pre><p>Now access MySQL:</p><pre>sudo mysql</pre><p>Create a production database:</p><pre>CREATE DATABASE laravel_production;</pre><pre>CREATE USER &#39;laravel_user&#39;@&#39;localhost&#39;<br>IDENTIFIED BY &#39;YOUR_STRONG_PASSWORD&#39;;</pre><pre>GRANT ALL PRIVILEGES ON laravel_production.*<br>TO &#39;laravel_user&#39;@&#39;localhost&#39;;</pre><pre>FLUSH PRIVILEGES;</pre><pre>EXIT;</pre><p>We have now created a dedicated database and database user for our Laravel application.</p><p>Avoid using the MySQL root account directly inside your application’s .env file.</p><h3>7. Upload Your Laravel Application to the VPS</h3><p>There are multiple ways to transfer your Laravel project to a production server:</p><ul><li>Git and GitHub</li><li>SCP or SFTP</li><li>CI/CD pipelines</li><li>Deployment automation tools</li></ul><p>For this tutorial, we’ll use Git.</p><p>Create a directory for your application:</p><pre>sudo mkdir -p /var/www/laravel-app</pre><p>Set the appropriate ownership for your deployment user, then clone your repository:</p><pre>sudo chown -R $USER:$USER /var/www/laravel-app</pre><pre>cd /var/www/laravel-app</pre><pre>git clone YOUR_GITHUB_REPOSITORY_URL .</pre><p>Your project structure should look similar to this:</p><pre>laravel-app/<br>│<br>├── app/<br>├── bootstrap/<br>├── config/<br>├── database/<br>├── public/<br>├── resources/<br>├── routes/<br>├── storage/<br>├── tests/<br>├── vendor/<br>├── artisan<br>├── composer.json<br>└── composer.lock</pre><p>The public directory is particularly important because it contains the application&#39;s public entry point.</p><h3>8. Install Laravel Dependencies</h3><p>Move into your project directory:</p><pre>cd /var/www/laravel-app</pre><p>Install production dependencies:</p><pre>composer install --no-dev --optimize-autoloader</pre><p>This command installs the dependencies required by your application without development-only packages.</p><p>If your project uses Vite, build your frontend assets as well.</p><p>Ideally, build these assets during your CI/CD process or on a separate build environment.</p><pre>npm ci<br>npm run build</pre><p>You can omit the Node.js build step if your application does not use a frontend build process.</p><h3>9. Configure the Production Environment</h3><p>Create your production .env file:</p><pre>cp .env.example .env</pre><p>Open it:</p><pre>nano .env</pre><p>Update the configuration:</p><pre>APP_NAME=LaravelApp<br>APP_ENV=production<br>APP_KEY=<br>APP_DEBUG=false<br>APP_URL=https://example.com</pre><pre>DB_CONNECTION=mysql<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=laravel_production<br>DB_USERNAME=laravel_user<br>DB_PASSWORD=YOUR_STRONG_PASSWORD</pre><p>Generate your Laravel application key:</p><pre>php artisan key:generate</pre><p>This generates the application encryption key.</p><p><strong>Important:</strong> Never regenerate the application key on every deployment. Existing encrypted data, cookies, and sessions may become invalid.</p><p>Also, ensure your .env file is excluded from Git.</p><h3>10. Configure Nginx for Laravel</h3><p>Now we need to configure Nginx to serve our Laravel application.</p><p>Create a new Nginx configuration file:</p><pre>sudo nano /etc/nginx/sites-available/laravel-app</pre><p>Add the following configuration:</p><pre>server {<br>    listen 80;<br>    server_name example.com www.example.com;</pre><pre>    root /var/www/laravel-app/public;</pre><pre>    index index.php index.html;</pre><pre>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }</pre><pre>    location ~ \.php$ {<br>        include snippets/fastcgi-php.conf;</pre><pre>        fastcgi_pass unix:/run/php/php8.3-fpm.sock;<br>    }</pre><pre>    location ~ /\.(?!well-known).* {<br>        deny all;<br>    }<br>}</pre><p>Replace example.com with your actual domain.</p><p>Make sure the PHP-FPM socket matches your installed PHP version.</p><p>Enable the configuration:</p><pre>sudo ln -s /etc/nginx/sites-available/laravel-app \<br>/etc/nginx/sites-enabled/</pre><p>Test the Nginx configuration:</p><pre>sudo nginx -t</pre><p>If the configuration is valid, reload Nginx:</p><pre>sudo systemctl reload nginx</pre><p><strong>Important:</strong> The Nginx document root must point to Laravel’s public directory, not the root directory of the Laravel project.</p><p>This prevents sensitive application files such as .env, composer.json, and application source code from being directly exposed through the web server.</p><h3>11. Configure Laravel File Permissions</h3><p>One of the most common problems during Laravel deployment is incorrect file permissions.</p><p>Laravel needs write access to:</p><ul><li>storage</li><li>bootstrap/cache</li></ul><p>For example, if Nginx and PHP-FPM run under the www-data user:</p><pre>sudo chown -R deploy:www-data /var/www/laravel-app</pre><p>Grant group write access to the required directories:</p><pre>sudo chmod -R ug+rwx storage bootstrap/cache</pre><p>Replace deploy with your actual deployment user.</p><p>Avoid using chmod -R 777 on your production application.</p><p>It creates unnecessary security risks.</p><h3>12. Run Database Migrations</h3><p>Once your database connection is configured, execute Laravel migrations:</p><pre>php artisan migrate --force</pre><p>The --force option allows migrations to run in a production environment without interactive confirmation.</p><p>If your application requires database seeders, run them separately when appropriate:</p><pre>php artisan db:seed --force</pre><p>Be careful when running seeders on production. Make sure they do not overwrite or delete existing customer data.</p><h3>13. Create the Storage Symbolic Link</h3><p>If your Laravel application stores uploaded images and documents using the public storage disk, create the symbolic link:</p><pre>php artisan storage:link</pre><p>This creates:</p><pre>public/storage -&gt; storage/app/public</pre><p>Now files stored inside the public storage disk can be accessed through URLs such as:</p><pre>https://example.com/storage/example.jpg</pre><p>Ensure your storage directory has the correct permissions.</p><p>For sensitive documents, use private storage and controlled download routes rather than public URLs.</p><h3>14. Enable Laravel Production Optimization</h3><p>Laravel provides several Artisan commands to optimize application performance.</p><p>Run:</p><pre>php artisan optimize</pre><p>This prepares Laravel’s configuration, route, event, and view caches where supported by your framework version.</p><p>You can also run the individual commands:</p><pre>php artisan config:cache</pre><pre>php artisan route:cache</pre><pre>php artisan view:cache</pre><p>Remember to clear or rebuild caches when changing configuration or deploying updated routes and views.</p><p>Avoid caching configuration while relying on runtime .env access in application code. Use Laravel&#39;s configuration system instead.</p><h3>15. Configure SSL and HTTPS</h3><p>Security is an essential part of production deployment.</p><p>You should always configure HTTPS for a public-facing Laravel application.</p><p>One popular option is Let’s Encrypt with Certbot.</p><p>Install Certbot:</p><pre>sudo apt install certbot python3-certbot-nginx -y</pre><p>Generate and install an SSL certificate:</p><pre>sudo certbot --nginx -d example.com -d www.example.com</pre><p>Follow the instructions provided by Certbot.</p><p>After successful configuration, your website should be accessible through:</p><pre>https://example.com</pre><p>Also verify automatic certificate renewal:</p><pre>sudo certbot renew --dry-run</pre><h3>16. Configure Laravel Scheduler</h3><p>If your application uses scheduled tasks, you need to configure Laravel’s scheduler on the production server.</p><p>Open the cron configuration:</p><pre>crontab -e</pre><p>Add:</p><pre>* * * * * cd /var/www/laravel-app &amp;&amp; php artisan schedule:run &gt;&gt; /dev/null 2&gt;&amp;1</pre><p>Laravel will now check scheduled tasks every minute.</p><p>This is useful for:</p><ul><li>Sending scheduled emails</li><li>Generating reports</li><li>Cleaning temporary files</li><li>Processing periodic business tasks</li><li>Running automated database operations</li></ul><p>Without this configuration, Laravel scheduled tasks will not execute automatically.</p><h3>17. Configure Laravel Queue Workers</h3><p>If your application uses Laravel queues for background jobs, you need to run queue workers in production.</p><p>For example:</p><pre>php artisan queue:work</pre><p>However, running this command manually in a terminal is not a reliable production solution.</p><p>You should use a process manager such as Supervisor to keep workers running and restart them when required.</p><p>Example Supervisor configuration:</p><pre>[program:laravel-worker]<br>process_name=%(program_name)s_%(process_num)02d<br>command=php /var/www/laravel-app/artisan queue:work --sleep=3 --tries=3 --timeout=90<br>autostart=true<br>autorestart=true<br>user=deploy<br>numprocs=2<br>redirect_stderr=true<br>stdout_logfile=/var/www/laravel-app/storage/logs/worker.log<br>stopwaitsecs=3600</pre><p>After saving the configuration, reload Supervisor:</p><pre>sudo supervisorctl reread</pre><pre>sudo supervisorctl update</pre><pre>sudo supervisorctl start laravel-worker:*</pre><p>After deploying new application code, restart the queue workers gracefully:</p><pre>php artisan queue:restart</pre><p>This allows existing workers to finish their current jobs before restarting.</p><h3>18. Common Laravel Deployment Errors and Solutions</h3><p>Even after following all the steps, you may encounter some common deployment problems.</p><p>Here are a few examples.</p><p><strong>Error 1: 500 Internal Server Error</strong></p><p>Possible reasons:</p><ul><li>Incorrect .env configuration</li><li>Missing PHP extensions</li><li>Incorrect file permissions</li><li>Application exceptions</li></ul><p>Check the Laravel log:</p><pre>tail -f storage/logs/laravel.log</pre><p><strong>Error 2: 404 Page Not Found</strong></p><p>Possible reasons:</p><ul><li>Incorrect Nginx configuration</li><li>Missing Laravel rewrite rules</li><li>Incorrect document root</li></ul><p>Make sure your Nginx root points to:</p><pre>/var/www/laravel-app/public</pre><p><strong>Error 3: Database Connection Failed</strong></p><p>Check:</p><ul><li>Database name</li><li>Username and password</li><li>MySQL service status</li><li>Database host and port</li></ul><p>Check MySQL:</p><pre>sudo systemctl status mysql</pre><p><strong>Error 4: Uploaded Images Not Showing</strong></p><p>Check whether the storage symbolic link exists:</p><pre>php artisan storage:link</pre><p>Also verify the storage directory permissions and the image’s actual path.</p><p><strong>Error 5: Permission Denied</strong></p><p>Check ownership and permissions:</p><pre>ls -la storage</pre><pre>ls -la bootstrap/cache</pre><p>Make sure PHP-FPM has the necessary write permissions.</p><h3>19. Laravel Deployment Best Practices</h3><p>Deploying an application is not just about making it accessible through a domain.</p><p>A reliable production environment also requires security, monitoring, backups, and maintenance.</p><p>Here are some practices every Laravel developer should follow:</p><ol><li>Always set APP_ENV=production.</li><li>Keep APP_DEBUG=false on production servers.</li><li>Never expose the .env file.</li><li>Use HTTPS with a valid SSL certificate.</li><li>Keep PHP, Laravel, Composer dependencies, and server packages updated.</li><li>Use Git for version control.</li><li>Configure automated database backups.</li><li>Monitor Laravel logs and server resources.</li><li>Use Supervisor for long-running queue workers.</li><li>Configure Laravel Scheduler through cron.</li><li>Use proper file permissions.</li><li>Avoid running application processes as root.</li><li>Use a staging environment before production deployment.</li><li>Automate deployments through CI/CD pipelines when possible.</li></ol><h3>20. Automate Laravel Deployment with CI/CD</h3><p>Once you understand manual deployment, the next step is automation.</p><p>Instead of manually connecting to your VPS and executing deployment commands every time you update your application, you can create a CI/CD pipeline.</p><p>Popular tools include:</p><ul><li>GitHub Actions</li><li>Jenkins</li><li>GitLab CI/CD</li><li>Docker</li><li>Ansible</li></ul><p>A basic deployment workflow looks like this:</p><pre>Developer<br>    |<br>    v<br>Git Push<br>    |<br>    v<br>GitHub Repository<br>    |<br>    v<br>CI/CD Pipeline<br>    |<br>    v<br>Install Dependencies<br>    |<br>    v<br>Run Tests<br>    |<br>    v<br>Deploy to VPS<br>    |<br>    v<br>Laravel Production</pre><p>For example, GitHub Actions can automatically trigger a deployment workflow whenever changes are pushed to a selected branch.</p><p>You can further improve the deployment process by introducing automated testing, rollback strategies, zero-downtime deployment techniques, and Docker-based environments.</p><p>This is where Laravel development and DevOps engineering start working together.</p><h3>Conclusion</h3><p>Deploying a Laravel application from localhost to a production VPS is an important milestone for every PHP developer.</p><p>Understanding Linux, Nginx, PHP-FPM, MySQL, Composer, SSL, file permissions, queues, and scheduled tasks helps you become more confident in managing real-world production applications.</p><p>As a developer, I believe learning deployment and infrastructure management alongside application development is extremely valuable.</p><p>It is not enough to know how to build an application. Understanding how to deploy, secure, monitor, and maintain it in production makes you a more complete software engineer.</p><p>I’m continuously exploring Laravel, Full Stack Development, DevOps, Cloud Computing, and AI-powered technologies to improve my development and infrastructure skills.</p><p><strong>What deployment approach do you prefer for Laravel applications: manual VPS deployment, Docker, or automated CI/CD pipelines?</strong></p><p>I’d love to hear about your experience and learn from other developers.</p><h3>About the Author</h3><p><strong>Vikash Kumar Singh</strong> is a Full Stack Developer specializing in PHP, Laravel, MySQL, and modern web application development. He also explores DevOps, Cloud Computing, Docker, Kubernetes, CI/CD automation, and Generative AI.</p><p>Portfolio: <a href="https://vikashkumar.pages.dev/">https://vikashkumar.pages.dev/</a></p><p>Always Learning. Always Building. Always Improving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c29ab8591372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Throttling vs Rate Limiting in Laravel]]></title>
            <link>https://medium.com/@vikash.dukeinfo/understanding-throttling-vs-rate-limiting-in-laravel-b06636357edd?source=rss-994d55690c46------2</link>
            <guid isPermaLink="false">https://medium.com/p/b06636357edd</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[throttling]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Vikash Kumar singh]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 06:59:24 GMT</pubDate>
            <atom:updated>2026-07-10T06:59:24.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pG66WKdGfaDk8O9x9xqHXA.png" /><figcaption>Rate Limiting Vs Throttling</figcaption></figure><p>When building a web application, one of the most important security concerns is preventing abuse. Whether it’s protecting your login page from brute-force attacks or limiting how often an API can be called, Laravel provides powerful tools to handle these scenarios.</p><p>Many developers use the terms <strong>throttling</strong> and <strong>rate limiting</strong> interchangeably, but they are not exactly the same.</p><p>In this article, we’ll understand the difference between them and see how Laravel implements both.</p><h3>What is Throttling?</h3><p><strong>Throttling</strong> is the process of slowing down or temporarily blocking a user after too many repeated actions within a short period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWAV3gcLJkjSNwWsBgWjcw.png" /><figcaption>Throttling</figcaption></figure><p>The most common example is the login page.</p><p>Imagine someone tries to guess a user’s password by submitting hundreds of login attempts. Instead of allowing unlimited attempts, Laravel temporarily locks that user out after a predefined number of failed attempts.</p><p>This is called <strong>login throttling</strong>.</p><p>Laravel Breeze and Fortify already include this protection.</p><h3>Example</h3><p>Consider the following method from Laravel’s authentication request:</p><pre>/** * Ensure the login request is not rate limited.<br> * * @throws \Illuminate\Validation\ValidationException<br> */<br> public function ensureIsNotRateLimited()<br> { <br>   if (! RateLimiter::tooManyAttempts($this-&gt;throttleKey(), 5))<br>   { <br>      return;<br>   }<br><br>   event(new Lockout($this));<br><br>   $seconds = RateLimiter::availableIn($this-&gt;throttleKey());<br>       throw ValidationException::withMessages(<br>       [ &#39;email&#39; =&gt; trans(&#39;auth.throttle&#39;,<br>         [ &#39;seconds&#39; =&gt; $seconds,<br>           &#39;minutes&#39; =&gt; ceil($seconds / 60),<br>         ]),<br>       ]);<br> }</pre><p>Let’s break it down.</p><h3>Step 1: Check the Number of Attempts</h3><pre>RateLimiter::tooManyAttempts($this-&gt;throttleKey(), 5)</pre><p>Laravel checks whether the current user has exceeded <strong>5 failed login attempts</strong>.</p><ul><li>throttleKey() creates a unique key.</li><li>Usually this key combines the email address and the user’s IP address.</li><li>This ensures one user’s failed attempts don’t affect another user.</li></ul><p>If the user has not exceeded the limit, the method simply returns and the login process continues.</p><pre>if (! RateLimiter::tooManyAttempts(...))<br> { <br>    return;<br> }</pre><h3>Step 2: Fire a Lockout Event</h3><pre>event(new Lockout($this));</pre><p>Laravel dispatches a Lockout event.</p><p>This event allows you to:</p><ul><li>Log security events</li><li>Send notifications</li><li>Trigger monitoring tools</li><li>Record suspicious activity</li></ul><h3>Step 3: Calculate Remaining Lock Time</h3><pre>$seconds = RateLimiter::availableIn($this-&gt;throttleKey());</pre><p>Laravel determines how many seconds remain before the user can try again.</p><p>Example:</p><pre>42 seconds remaining</pre><h3>Step 4: Throw a Validation Exception</h3><pre>throw ValidationException::withMessages([<br>    &#39;email&#39; =&gt; trans(&#39;auth.throttle&#39;, [<br>        &#39;seconds&#39; =&gt; $seconds,<br>        &#39;minutes&#39; =&gt; ceil($seconds / 60),<br>    ]),<br>]);</pre><p>Instead of processing the login request, Laravel throws a validation error.</p><p>The user sees a message similar to:</p><blockquote><em>Too many login attempts. Please try again in 42 seconds.</em></blockquote><h3>What is Rate Limiting?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*3d5xpRNkxwJcrQVCH9b9AQ.png" /><figcaption>Rate Limiting</figcaption></figure><p><strong>Rate limiting</strong> is a technique used to control how many requests a client can make to an application within a specific period of time. It acts as a protective layer between your application and its users by restricting excessive or abusive requests.</p><p>For example, imagine an API that allows users to fetch product information. Without rate limiting, a malicious user or bot could send thousands of requests every second, consuming server resources and potentially making the application unavailable for legitimate users.</p><p>Rate limiting solves this problem by defining rules such as:</p><ul><li>60 requests per minute</li><li>5 OTP requests every 10 minutes</li><li>100 API requests per hour</li><li>3 contact form submissions per minute</li></ul><p>Once the limit is reached, the server temporarily rejects additional requests until the configured time window resets.</p><h3>Why is Rate Limiting Important?</h3><p>Implementing rate limiting provides several benefits:</p><ul><li><strong>Protects against abuse:</strong> Prevents bots and malicious users from overwhelming your application.</li><li><strong>Improves security:</strong> Reduces brute-force attacks on login forms, APIs, and authentication endpoints.</li><li><strong>Ensures fair usage:</strong> Prevents a single user from consuming excessive server resources.</li><li><strong>Improves application stability:</strong> Keeps your application responsive during periods of heavy traffic.</li><li><strong>Reduces infrastructure costs:</strong> Fewer unnecessary requests mean lower CPU, memory, and bandwidth usage.</li></ul><h3>Real-World Examples</h3><p>Rate limiting is commonly used in modern applications for scenarios such as:</p><ul><li><strong>REST APIs:</strong> Limit clients to 100 requests per minute.</li><li><strong>OTP Verification:</strong> Allow only 5 OTP requests every 10 minutes.</li><li><strong>Password Reset:</strong> Restrict reset email requests to prevent spam.</li><li><strong>Contact Forms:</strong> Prevent repeated form submissions.</li><li><strong>Search Endpoints:</strong> Stop automated bots from scraping data.</li><li><strong>File Uploads:</strong> Limit upload frequency to protect server resources.</li></ul><h3>How Laravel Implements Rate Limiting</h3><p>Laravel provides the RateLimiter facade and the throttle middleware to implement rate limiting with minimal code. You can define custom limits based on a user&#39;s ID, IP address, email address, or any unique identifier.</p><p>For example, the following limiter allows each IP address to make only <strong>5 requests per minute</strong>:</p><pre>use Illuminate\Cache\RateLimiting\Limit;<br>use Illuminate\Support\Facades\RateLimiter;<br>use Illuminate\Http\Request;</pre><pre>RateLimiter::for(&#39;contact-form&#39;, function (Request $request) {<br>    return Limit::perMinute(5)-&gt;by($request-&gt;ip());<br>});</pre><p>You can then apply this limiter to a route:</p><pre>Route::post(&#39;/contact&#39;, ContactController::class)<br>    -&gt;middleware(&#39;throttle:contact-form&#39;);</pre><p>If a client exceeds the configured limit, Laravel automatically returns an HTTP <strong>429 (Too Many Requests)</strong> response, indicating that the client must wait before making additional requests.</p><h3>In Simple Terms</h3><p>Think of rate limiting like the entrance gate at a stadium. The gate allows only a certain number of people to enter within a given time. Once that limit is reached, everyone else must wait until entry is allowed again.</p><p>Similarly, rate limiting ensures that your application remains secure, stable, and available by controlling how frequently users can access its resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b06636357edd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>