Laravel

Fixing SQLSTATE[HY000] [1045] Access Denied for User 'root'@'localhost' in Laravel & MySQL 8


You run php artisan migrate or load your Laravel application in the browser, and PDO immediately rejects the database handshake with one of two errors:

Illuminate\Database\QueryException

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

Or:

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

Unlike connection refusal errors where the database server is unreachable, error 1045 proves that MySQL or MariaDB is running and actively listening—it simply rejected your credentials, authentication plugin, or client host origin.


Quick Diagnostic Reference

Look at the exact user, host IP, and password flag in your error message to jump to the matching fix:

Terminal Error Signature Root Cause Jump to Fix
(using password: NO) even though DB_PASSWORD is set Cached config.php or unquoted # character in .env Fix 1
(using password: YES) with #, $, or spaces in password Dotenv parser truncated or interpolated your password string Fix 1
Fresh Ubuntu / Debian VPS using root@localhost MySQL 8 defaults root to OS-level auth_socket instead of password Fix 2
'sail'@'172.18.0.x' or Docker container IP rejected Persistent Docker volume was initialized with older .env credentials Fix 3
Custom DB user works via CLI TCP, fails on localhost MySQL grant mismatch between 'user'@'%' and 'user'@'localhost' Fix 4

1. The .env Special Character Trap & Stale Config Cache

Before altering users inside MySQL, verify what password string Laravel is actually sending over the wire.

A. Unquoted # and $ Characters in .env

Laravel uses the vlucas/phpdotenv library to parse your .env file. If your database password contains a hash (#), dollar sign ($), exclamation mark (!), or spaces, and you do not wrap the password in double quotes, the parser corrupts the value:

  • Anything after an unquoted # is stripped out as an inline comment.
  • Anything following a $ (e.g., MyPass$123) is evaluated as an environment variable reference, replacing $123 with an empty string.

Always wrap complex passwords in double quotes inside .env:

# ❌ BROKEN: Parser treats #secret99 as a comment, sending only "MyPass"
DB_PASSWORD=MyPass#secret99

# ❌ BROKEN: Parser evaluates $admin as an empty variable
DB_PASSWORD= Super$admin2026

# ✅ WORKING: Wrapped in double quotes with no leading space after =
DB_PASSWORD="MyPass#secret99"

B. Clearing a Locked Configuration Cache

If your error message says (using password: NO) despite having a password in .env, Laravel is ignoring your .env file completely and reading from a previously compiled bootstrap/cache/config.php file.

Clear the cached configuration and test again:

php artisan config:clear

(Note: If running php artisan config:clear fails to delete the cached file on your server or throws a file write error, your web user lacks group ownership of bootstrap/cache. See our guide on Fixing storage/logs/laravel.log Permission Denied in Linux & Docker to fix directory permissions safely).


2. Ubuntu / Debian MySQL 8 auth_socket Trap (root@localhost)

On modern Ubuntu (22.04 LTS / 24.04 LTS) and Debian servers, you can log into MySQL from the terminal by typing sudo mysql without entering a password. However, when Laravel tries to connect as root, it fails with 1045 Access denied.

Why this happens:

By default, MySQL 8 on Ubuntu configures the root account to use the auth_socket plugin instead of a password. The auth_socket plugin checks whether the Linux operating system user (UID) running the command matches root. Because PHP-FPM and Artisan run under www-data or your deployment user—not Linux root—MySQL blocks the connection.

The Production-Safe Fix: Create a Dedicated Application User

Instead of weakening the system root account, open the MySQL shell via sudo and create a dedicated database user for your Laravel app:

sudo mysql

Run these SQL commands inside the MySQL prompt:

-- 1. Create your database if it doesn't exist yet
CREATE DATABASE IF NOT EXISTS laravel_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 2. Create a dedicated user for both TCP (127.0.0.1) and Socket (localhost)
CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'StrongPassword_2026!';
CREATE USER 'laravel_user'@'127.0.0.1' IDENTIFIED BY 'StrongPassword_2026!';

-- 3. Grant privileges only to your application database
GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'localhost';
GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'127.0.0.1';

FLUSH PRIVILEGES;
EXIT;

Then update your .env file to use the dedicated credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=laravel_user
DB_PASSWORD="StrongPassword_2026!"

Alternative (Local Development Machines Only):

If you are working on a local Linux machine and specifically want root to accept standard passwords over TCP, switch root to caching_sha2_password:

ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'your_local_password';
FLUSH PRIVILEGES;

3. Docker Compose & Laravel Sail ('sail'@'172.18.0.x')

When running Laravel inside Docker or Laravel Sail, the error usually shows a bridge network IP address instead of localhost:

SQLSTATE[HY000] [1045] Access denied for user 'sail'@'172.18.0.5' (using password: YES)

Why this happens:

Official MySQL and MariaDB Docker images only read MYSQL_DATABASE, MYSQL_USER, and MYSQL_PASSWORD from your .env file the very first time the container boots with an empty data volume.

If you start your containers once, and later change DB_USERNAME or DB_PASSWORD in your .env file, the existing persistent Docker volume (/var/lib/mysql) ignores your .env changes and keeps requiring the old password.

(Note: Ensure your DB_HOST in Docker is set to your service name, such as DB_HOST=mysql, rather than 127.0.0.1. If changing DB_HOST causes a socket or port refusal error, see our guide on Fixing SQLSTATE[HY000] [2002] Connection Refused in Laravel).

Option A: Wipe and Re-Initialize the Docker Volume (Local Dev)

If you do not have local data you need to keep, stop the containers with the -v flag to destroy the stale database volume and rebuild it from your current .env:

# Using Laravel Sail:
./vendor/bin/sail down -v
./vendor/bin/sail up -d

# Or using standard Docker Compose:
docker compose down -v
docker compose up -d

Option B: Update Password Without Losing Data

If your Docker volume contains data you cannot wipe, sync the MySQL user’s password inside the running container to match your .env file:

docker compose exec mysql mysql -u root -p

Once inside the container’s MySQL prompt, update the password for the % wildcard host:

ALTER USER 'sail'@'%' IDENTIFIED BY 'your_new_env_password';
GRANT ALL PRIVILEGES ON *.* TO 'sail'@'%';
FLUSH PRIVILEGES;
EXIT;

4. The 'user'@'%' vs. 'user'@'localhost' Host Mismatch

A subtle quirk in MySQL and MariaDB is how host wildcards work:

  • 'user'@'%' matches any TCP/IP connection (including 127.0.0.1), but it does NOT include localhost.
  • 'user'@'localhost' matches connections made over the local Unix domain socket (mysql.sock).

If you created a user with CREATE USER 'app'@'%' and your Laravel .env has DB_HOST=localhost, MySQL resolves the connection as 'app'@'localhost', ignores the 'app'@'%' password grant, and throws 1045 Access denied.

How to fix it:

In your Laravel .env, always set DB_HOST=127.0.0.1 instead of localhost to force a clean TCP/IP connection:

DB_HOST=127.0.0.1

You can inspect exactly which user-and-host combinations exist in your database by running:

SELECT user, host, plugin FROM mysql.user;

Verification & Post-Connection Checks

Once you have updated your user grants or .env configuration, clear Laravel’s cached state and verify the database connection using Artisan’s built-in monitor command (available in Laravel 10, 11, and 12):

php artisan config:clear
php artisan db:show

If php artisan db:show prints your database engine, version, and open connections count, your authentication is fixed. You can now run your migrations:

php artisan migrate
  • If migrate fails mid-run with 1071 Specified key was too long: Your MySQL/MariaDB storage engine defaulted to MyISAM or legacy index limits. Read our walkthrough on Fixing SQLSTATE[42000]: 1071 Specified Key Was Too Long.
  • If you were getting 419 Page Expired before fixing your database: Because Laravel 11 and 12 store user sessions in the database by default (SESSION_DRIVER=database), resolving this database connection and migrating the sessions table will also restore session persistence. For SPA or proxy issues, check Fixing Laravel 419 Page Expired (CSRF Token Mismatch).