Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

soduno's avatar
Level 1

Artisan cant connect to db, but localhost can

When I use localhost in the browser, laravel can perfectly fine connect to the database, though when using artisan commands e.g. like php artisan migrate - it cant connect, only if i change host from mysql to 127.0.0.1. But when using 127.0.0.1 localhost cant connect to db, So atm. i'm always changing the host and its a bit annoying.

Is there anyway to forward, or setting it up correctly? Below is my connection details:

Works with localhost: DB_CONNECTION=mysql DB_HOST=mysql DB_PORT=3306 DB_DATABASE=local_dev_db DB_USERNAME=sail DB_PASSWORD=password

Works with artisan commands DB_CONNECTION=127.0.0.1 DB_HOST=mysql DB_PORT=3306 DB_DATABASE=local_dev_db DB_USERNAME=sail DB_PASSWORD=password

Using WSL2 Windows with Sail docker, writing artisan commands in ubuntu terminal.

0 likes
6 replies
soduno's avatar
Level 1

So minutes after, I solved it using environment variables differ from localhost to artisan and created a special bash alias forwarding host variable to 127.0.0.1 php artisan

martinbean's avatar

@soduno How are you actually serving your Laravel project? XAMPP? Sail? Something else?

1 like
soduno's avatar
Level 1

@martinbean True, I forgot that - thanks. I've setup a new alias in bash works perfectly :)

1 like
browntown's avatar

@soduno Can you share more of what you did? I've been running into the same issue and I'd love to see your solution. Thanks.

Please or to participate in this conversation.