182

I'm on a Mac OS Yosemite using Laravel 5.0.

While in my local environment, I run php artisan migrate I keep getting :

Access denied for user 'homestead'@'localhost' (using password: YES)

Configuration

Here is my .env

APP_ENV=local
APP_DEBUG=true
APP_KEY=*****

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

app\config\database.php

   'mysql'       => [
    'driver'      => 'mysql',
    'host'        => env('DB_HOST', 'localhost'),
    'database'    => env('DB_DATABASE', 'homestead'),
    'username'    => env('DB_USERNAME', 'homestead'),
    'password'    => env('DB_PASSWORD', 'secret'),
    'unix_socket' => '/tmp/mysql.sock',
    'charset'     => 'utf8',
    'collation'   => 'utf8_unicode_ci',
    'prefix'      => '',
    'strict'      => false,
    ]

How do I avoid this kind of error ?

I've tried :


1

in app/database.php

Replace localhost with 127.0.0.1

'host'=> env('DB_HOST', 'localhost') -->'host' => env('DB_HOST', '127.0.0.1')

Also, in .env

DB_HOST=localhost --> DB_HOST=127.0.0.1


2

Try specify environment

php artisan migrate --env=local


3

Check to see if the MySQL is running by run

mysqladmin -u homestead -p status Enter password: secret

I got

Uptime: 21281 Threads: 3 Questions: 274 Slow queries: 0 Opens: 327 Flush tables: 1 Open tables: 80 Queries per second avg: 0.012

Which mean it's running.


4

Check MySQL UNIX Socket (This step work for me)

Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604
  • 1
    best practice would be to ensure that the account actually exists in mysql... "I found this key on the street, and it doesn't work in my front door lock. How can I change the lock to make the key work?" – Marc B Apr 20 '15 at 19:06
  • 1
    I take it you're using the homestead VM? I have found that it will only work when you're in the VM. you can get onto it via ssh vagrant@127.0.0.1 -p 2222. my default machine doesn't twig that said db is running. – Jay Edwards Sep 12 '15 at 18:44

32 Answers32

264

The reason of Access denied for user ‘homestead’@’localhost’ laravel 5 error is caching-issue of the .env.php file cause Laravel 5 is using environment based configuration in your .env file.

1. Go to your application root directory and open .env file (In ubuntu may be it’s hidden so press ctrl+h to show hidden files & if you are in terminal then type : ls -a to show hidden files) in your editor and change database configuration setting. then save your .env file

DB_HOST=localhost
DB_DATABASE=laravelu
DB_USERNAME=root
DB_PASSWORD=''

2. then restart your apache server/web server. and refresh your page and you have done

3. If still issue try to run below command to clear the old configuration cache file.

php artisan config:clear

Now you are done with the error

J4GD33P 51NGH
  • 630
  • 1
  • 8
  • 24
Abdou Tahiri
  • 4,338
  • 5
  • 25
  • 38
  • 1
    I worked for me thanks, one question why we have to set our db details on .env file as we do it on database.php file – Dipen Jan 17 '16 at 05:21
  • 1
    maybe i you need multiple environment ,, production and local . – Abdou Tahiri Jan 17 '16 at 13:34
  • Worked for me, thanks. Step 2 doesn't seem to be necessary, at least not in my case. – Gonzalo Larralde Mar 15 '16 at 04:58
  • 5
    Kept trying to restart Apache when I was using "php artisan serve" the whole time, I would suggest you don't make the same mistake as me > – Carlton May 24 '16 at 23:23
  • 1
    Does not work, and now I get `PDOException in Connector.php line 55: SQLSTATE[HY000] [1049] Unknown database 'laravelu'` ._. – Black Feb 12 '17 at 10:21
  • 1
    I tried changing `.env` and `config:clear` `cache:clear` all command, restarted `apache` but still getting the same problem. – Luzan Baral May 08 '17 at 11:41
  • Very important detail I found to solve my problem in this case was that the password value has to be enclosed within quotes (single/double) unlike most other variables within the .env file. – Shully Aug 17 '22 at 06:19
70

TLDR: You need to stop the server Ctrl + c and start again using php artisan serve


Details:

If you are using Laravel, and have started local dev server already by php artisan serve

And after having above server already running, you change your database server related stuff in .env file. Like moving from MySQL to SQLite or something. You need to make sure that you stop above process i.e. Ctrcl C or anything which stop the process. And then restart Artisan Serve again i.e. y php artisan serve and refresh your browser and your issue related to database will be fixed. This is what worked for me for Laravel 5.3

Muhammad Asadullah
  • 3,735
  • 1
  • 22
  • 38
34

Two way to solve it

First way (Not recommended)

Open your database config file (laravel_root/config/database.php) & search for the below code block.

        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'blog'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),

Change the code block as below

        'host'      => 'yourHostName',
        'database'  => 'YourDatabastName',
        'username'  => 'YoutDatabaseUsername',
        'password'  => 'YourDatabasePassword',

Second way (Recommended by Laravel)

Check your Laravel root there have a file call .env if not exist, look for .env.example, copy/rename it as .env after that the file looks blow !

APP_ENV=local
APP_DEBUG=true
APP_KEY=someRandomNumber

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Modify the below block as follow

DB_HOST=yourHostName
DB_DATABASE=yourDatabaseName
DB_USERNAME=yourDatabaseUsername
DB_PASSWORD=youPassword

Now it will work fine.

abSiddique
  • 11,647
  • 3
  • 23
  • 30
  • 1
    What's the point of this file? This information is in `root/config/database.php` seems redundant. – Halter Feb 19 '17 at 13:13
  • The information dose not redundant, it's using env function to read the value from the .env file to secure server information. – abSiddique Feb 20 '17 at 18:39
  • How do you find or create your host name, database name, username and password with Homestead? – Connor Leech Jul 26 '19 at 22:34
23

if you are using php artisan migrate NOT from vagrant box but from host machine then you must define inside the .env the ip of the box 192.168.10.10

and obviously set permission to homestead user from your ip something like

grant all privileges on *.* to 'homestead'@% identified by 'secret';

in .env file

DB_HOST=192.168.10.10
DB_DATABASE=homestead
DB_USERNAME=homestead
wdog
  • 612
  • 6
  • 7
  • I couldn't get that to work, but `grant all privileges on *.* to 'homestead'@'localhost' identified by 'secret';` worked for me. – Ryan May 22 '18 at 23:00
21

If you are using the PHP's default web server (e.g. php artisan serve) you need to restart your server after changing your .env file values.

Vrushal Raut
  • 1,050
  • 2
  • 15
  • 20
12

I had the same issue and in the end It turned out that I just had to restart the server and start again

Ctrl + c then

php artisan serve
Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
124697
  • 22,097
  • 68
  • 188
  • 315
11

When you install Homestead, this creates a default "homestead" database in the VM. You should SSH into the VM homestead ssh and run your migrations from there. If you are working locally with no VM, you'll need to create your database manually. By default, the database should be called homestead, the username is homestead and the password is secret.

check this thread on laracasts or this blog post for more details


if you are getting

[PDOException] SQLSTATE[HY000] [2002] No such file or directory

try changing "host" in the /app/config/database.php file from "localhost" to "127.0.0.1" . you can find more details and other fixes here on this thread.

Also check whether you have specified the correct unix_socket . check this thread .

Community
  • 1
  • 1
Sojan Jose
  • 3,168
  • 6
  • 33
  • 52
  • @rangerover.js try changing "host" in the /app/config/database.php file from "localhost" to "127.0.0.1" – Sojan Jose Apr 20 '15 at 19:29
  • @rangerover.js check this thread http://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory . see any of the solutions matter. – Sojan Jose Apr 20 '15 at 19:37
  • @rangerover.js also check whether mysql service is running :) – Sojan Jose Apr 20 '15 at 19:39
  • @rangerover.js can check your unix_socket ? http://stackoverflow.com/a/25649930/939299 – Sojan Jose Apr 20 '15 at 20:44
  • 1
    It finally work on the 4th tried. Please delete all your comments, and include this link stackoverflow.com/a/25649930/939299 as part of your answer because it help me. – code-8 Apr 21 '15 at 02:58
  • @rangerover.js the next person having this error be having a different reason for it. The comments will help him debug cause all those are possible reasons :) . glad it worked for you . – Sojan Jose Apr 21 '15 at 07:00
  • Wasted 2 days fiddling with trying to get my DB migrated into a laravel app, the yellow box up top saved me anymore wasted time. Thank you! – Zach Tackett Sep 25 '18 at 15:45
11

Check MySQL UNIX Socket

Find unix_socket location using MySQL

mysql -u homestead -p

mysql> show variables like '%sock%';
+-----------------------------------------+-----------------------------+
| Variable_name                           | Value                       |
+-----------------------------------------+-----------------------------+
| performance_schema_max_socket_classes   | 10                          |
| performance_schema_max_socket_instances | 322                         |
| socket                                  | /var/run/mysqld/mysqld.sock |
+-----------------------------------------+-----------------------------+
3 rows in set (0.00 sec)

Then I go to config/database.php

I update this line : 'unix_socket' => '/tmp/mysql.sock',

to : 'unix_socket' => '/var/run/mysqld/mysqld.sock',

That's it. It works for my as my 4th try.I hope these steps help someone. :D

Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604
9

In Windows PC Follow below.


  1. Access the Root folder of your application.

  2. Edit the .env file

Access Root folder of your application

Edit the .env File

Edit the Highlighted and change the UserName and the password adn The database Name accordingly.

Fred Ondieki
  • 2,314
  • 25
  • 23
9

in my case, after restarting my server the problem was gone.

exit/close the "php artisan serve" command and

re-run the command "php artisan serve" command.

sh6210
  • 4,190
  • 1
  • 37
  • 27
9

in my case (laravel 5+) i had to wrap my password in single quotation marks and clear config cache:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=user_name
DB_PASSWORD='password'

and then run:

php artisan config:clear
mh. bitarafan
  • 886
  • 9
  • 16
8

Sometime in the future. Try to clear your config first

php artisan config:clear. 

Close all the terminal /cmd windows and then restart terminal/CMD and this should get rid of the error message. See if it works.

Krishneil
  • 1,432
  • 1
  • 18
  • 26
6

after config db restart the:

 php artisan serve

If the serve is active before set db config.

A1Gard
  • 4,070
  • 4
  • 31
  • 55
5

i using laravel 5.* i figure i have a file call .env in the root of the project that look something like this:

APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

And that was over writing the bd configuration so you can wheather deleted those config vars so laravel take the configuration under /config or set up your configuration here.

I did the second and it works for me :)

Jesus Gonzalez
  • 127
  • 2
  • 2
5

Got it! Log in as root and grant homestead@localhost the rights to everything.

From your terminal:

$ homestead ssh

$ mysql -u root -p

Enter password: secret

mysql> grant all privileges on *.* to 'homestead'@'localhost' identified by 'secret';

Query OK, 0 rows affected (0.00 sec)
exit

Now homesteads regular user has access to all of your tables, and as such, should be able to run things like migrations.

Mike Wright
  • 111
  • 1
  • 2
5

After change .env with the new configuration, you have to stop the server and run it again (php artisan serve). Cause laravel gets the environment when it's initialized the server. If you don't restart, you will change the .env asking yourself why the changes aren't taking place!!

Luis Lopez
  • 561
  • 1
  • 10
  • 29
5

All you have to do is alter your .env file.

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

In front of DB_DATABASE, write the name of the database and in front of DB_USERNAME, use root.

Apoorv
  • 184
  • 1
  • 2
4

I just wanted to post this because this issue frustrated me for about 3 hours today. I have not tried any of the methods listed in the other answers, though they all seem reasonable. In fact, I was just about to try going through each of the above proposed solutions, but somehow I got this stroke of inspiration. Here is what worked for me to get me back working -- YMMV:

1) Find your .env file. 2) Rename your .env file to something else. Laravel 5 must be using this file as an override for settings somewhere else in the framework. I renamed mine to .env.old 3) You may need to restart your web server, but I did not have to.

Good luck!

3

You have to run the $ php artisan migrate command from within Homestead, not your Mac.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • Your screen-shot shows the machine name as `MBP-bheng-aveniors`. That is _not_ your VM. You need to SSH into Homestead (`$ homestead ssh`) and then run `$ php artisan migrate` from within that SSH session. – Martin Bean Apr 20 '15 at 20:09
3

Check your ".env" file in the root folder. is it correct?

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Ferhat KOÇER
  • 3,890
  • 1
  • 26
  • 26
3

i have find solution

  1. Go to your application root directory and open .env file (In ubuntu may be it’s hidden so press ctrl+h to show hidden files) in your editor and change database configuration setting. then save your .env file

  2. then restart your apache server/web server. and refresh your page and you have done

  3. If still issue try to run below command to clear the old configuration cache file.

This worked for me gl ...

DucaBgd
  • 276
  • 3
  • 4
3

just change these things in the .env file of your root folder.

DB_DATABASE=your_db_name
DB_USERNAME=your_db_user_name
DB_PASSWORD='your_db_password'

It worked for me.

sradha
  • 2,216
  • 1
  • 28
  • 48
1

Log into MYSQL - use the mysql database.

Select * from User;

Make sure that your HOST column is correct. It should be the host that you are connecting from (your application server) be it IP address, or DNS name. Also '%' will work (meaning wildcard) but will not be secure.

beiller
  • 3,105
  • 1
  • 11
  • 19
1

Check your .env file, if you have edited any of the variables, kindly restart laravel server, and your problem will be solved

Ogbonna Vitalis
  • 7,969
  • 2
  • 11
  • 21
1

A. After updating the .env file with database settings, clear laravel setting by "running php artisan config:clear"

B. Please make sure you restart your apache server / rerun the "php artisan serve" command for your settings to take effect.

Legionar
  • 7,472
  • 2
  • 41
  • 70
Helper -Joe
  • 101
  • 6
0

I had the same issue using SQLite. My problem was that DB_DATABASE was pointing to the wrong file location.

Create the sqlite file with the touch command and output the file path using php artisan tinker.

$ touch database/database.sqlite
$ php artisan tinker
Psy Shell v0.8.0 (PHP 5.6.27 — cli) by Justin Hileman
>>> database_path(‘database.sqlite’)
=> "/Users/connorleech/Projects/laravel-5-rest-api/database/database.sqlite"

Then output that exact path to the DB_DATABASE variable.

DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=/Users/connorleech/Projects/laravel-5-rest-api/database/database.sqlite
DB_USERNAME=homestead
DB_PASSWORD=secret

Without the correct path you will get the access denied error

Connor Leech
  • 18,052
  • 30
  • 105
  • 150
0

If you have an error returning something like PDOException in Connector.php line 55: SQLSTATE[HY000] [1049] Unknown database 'laravelu' is due to you are changing your batabase config as DB_DATABASE=laravelu. So for now you either:

  1. Change the DB_DATABASE=[yourdatabase] or
  2. create a database called laravelu in your phpmyadmin

this should be able to solve it

Byron Wong
  • 145
  • 9
0

In my case the error was "caused" by my Homestead / Vagrant configuration about which I forgot :) trying to run the migration just from command line.

In case of using Homestead Vagrant Box environment you should run your migration from within your Homestead machine (after connecting to it using ssh: vagrant@192.168.10.10:22) then the access rights will be OK and will allow the migration to run.

Picard
  • 3,745
  • 3
  • 41
  • 50
0

From your question, it seems you are running homestead. In that case, make sure you're running the commands in your VM. Many devs including me often make mistake and run artisan commands outside of VM which the commands will try to connect to our local database accessible through localhost which is different from the database used by homestead. Cd to your Homestead directory and run

vagrant ssh

then cd into code if that is where you keep your projects and cd into your project and run php artisan migrate again I hope this will help other people.

Abdellah Ramadan
  • 367
  • 4
  • 15
0

My app had been set up to use .env.local. I was checking .env the whole time.

Check that you are editing the correct .env file if you have several.

watkib
  • 347
  • 3
  • 11
  • 25
0

in my case, i had not created the database by that name. Try changing the username, password and database name to suit what you have or visit :https://5balloons.info/fix-access-denied-for-user-homesteadlocalhost/

muli
  • 47
  • 1
  • 3
0

If using Laravel Dusk with GitHub Actions

I ran into this issue trying to set up a CI/CD pipeline with Laravel Dusk, using the default GitHub Action workflow in the Dusk documentation, which - as I've come to except for anything related to Dusk - is lacking.

I fixed it by adding my database environment variables from my .env.dusk.testing file to the GitHub Actions workflow, to make sure that the GitHub Actions runner had access to them. I also optionally moved them from the "Run Dusk" step to the job-level, making them available to any other steps in the job:

name: CI

on: [push]

jobs:
  dusk-php:
    env:
      APP_URL: "http://127.0.0.1:8000"
      DB_DATABASE: CICD_test_db
      DB_USERNAME: root
      DB_PASSWORD: root
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Prepare The Environment
        run: cp .env.example .env
      - name: Create Database
        run: |
          sudo systemctl start mysql
          mysql --user="root" --password="root" -e "CREATE DATABASE CICD_test_db character set UTF8mb4 collate utf8mb4_bin;"
      - name: Install Composer Dependencies
        run: composer install --no-progress --prefer-dist --optimize-autoloader
      - name: Generate Application Key
        run: php artisan key:generate
      - name: Upgrade Chrome Driver
        run: php artisan dusk:chrome-driver `/opt/google/chrome/chrome --version | cut -d " " -f3 | cut -d "." -f1`
      - name: Start Chrome Driver
        run: ./vendor/laravel/dusk/bin/chromedriver-linux &
      - name: Run Laravel Server
        run: php artisan serve --no-reload &
      - name: Run Dusk Tests
        run: php artisan dusk --env=testing -vvv
      - name: Upload Screenshots
        if: failure()
        uses: actions/upload-artifact@v2
        with:
          name: screenshots
          path: tests/Browser/screenshots
      - name: Upload Console Logs
        if: failure()
        uses: actions/upload-artifact@v2
        with:
          name: console
          path: tests/Browser/console
Hashim Aziz
  • 4,074
  • 5
  • 38
  • 68