You’re getting:
SQLSTATE[HY000] [1040] Too many connections
This happens when too many MySQL connections are opened at the same time (heavy traffic, bots, infinite loops, slow queries, or duplicate requests).
Yes—duplicate emails are a separate data issue, but they don’t directly cause “too many connections”. Still, you should clean duplicates + enforce unique, and also add rate limiting to stop bots/hits.
Below are both parts: (A) SQL to remove duplicate emails, (B) full Laravel code for rate limiting + practical DB connection fixes.
ERROR
SOLUTION
USING SQL
USING RATE LIMITING
[read blog first for middleware concept (https://www.debug.school/rakeshdevcotocus_468/implementing-canonical-url-redirects-using-laravel-middleware-3i9e)
SQL: Find duplicate emails and delete extra rows (keep 1)
See which emails are duplicated
SELECT email, COUNT(*) AS total
FROM users
WHERE email IS NOT NULL AND email <> ''
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY total DESC;
Delete duplicates and keep the lowest id per email (SAFE METHOD)
(Make a backup first.)
DELETE u1
FROM users u1
JOIN users u2
ON u1.email = u2.email
AND u1.id > u2.id
WHERE u1.email IS NOT NULL AND u1.email <> '';
This keeps the smallest id row for each email and deletes the rest.
Add unique index so it never happens again
If you want email to be unique:
ALTER TABLE users
ADD UNIQUE KEY users_email_unique (email);
If this fails, it means duplicates still exist. Run step 2 again and re-check.
ANOTHER SOLUTION
[read blog first for middleware concept (https://www.debug.school/rakeshdevcotocus_468/implementing-canonical-url-redirects-using-laravel-middleware-3i9e)
Full Laravel code: Rate limiting (Web + API + Login)
1) Create a middleware for web routes (blocks bots fast)
Create file:
app/Http/Middleware/RateLimitWeb.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\RateLimiter;
class RateLimitWeb
{
public function handle(Request $request, Closure $next): Response
{
// Key: IP + path (so bot can't hammer same URL)
$key = 'web:' . $request->ip() . ':' . sha1($request->path());
// Allow 60 requests per minute per IP per page
if (RateLimiter::tooManyAttempts($key, 60)) {
$retryAfter = RateLimiter::availableIn($key);
return response()->json([
'message' => 'Too many requests. Please try again later.',
'retry_after_seconds' => $retryAfter,
], 429);
}
RateLimiter::hit($key, 60);
return $next($request);
}
}
Register it in:
app/Http/Kernel.php
protected $routeMiddleware = [
// ...
'rate.web' => \App\Http\Middleware\RateLimitWeb::class,
];
Top comments (0)