Emil
Emil

Reputation: 21

Laravel choosing wrong database

I host an Apache PHP server on which there's a couple of websites. Let's call these X and Y.

After I cleared the cache (and made some changes) on both my laravel websites, I get the following error often:

[previous exception] [object] (PDOException(code: 42S02): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'Y.events_ip' doesn't exist at C:\\Apache24\\htdocs\\X\\vendor\\doctrine\\dbal\\lib\\Doctrine\\DBAL\\Driver\\PDOConnection.php:78)

It seems that the X website wants to use the Y website's database, even though the .env file is setup correctly and has the X website's database in it.

Things I have tried:
Restarting apache
Deleting cache of the laravel application
Checking the configuration in the .env file as well as the config/database file

Upvotes: 1

Views: 417

Answers (2)

f.strazzante
f.strazzante

Reputation: 103

In my case it was a conflict of .env files.

I was using WAMP with PHP 8.1.0 and MySQL 8.0.27 with Apache virtual-hosts. I had 2 Laravel sites A and B both with .env files. I could see them at a.test and b.test (using Wamp Apache virtual-hosts) and via browser they work fine. A eventually call B via GET/POST call. At that point I got an error in B because B was trying to load the database of A.

I realized that the root of the problem was that if a function of B was loaded after a few ms of the function of A, the .env value was not correct.

I thought it might makes sense because it was running on the same server (my PC) and with the same PHP.

Laravel give us great tools to manage the environment values which are the config files and the cache of the config files. Caching the config file will allow the website to be faster and to isolate all the .env values. All that you have to do is load the .env values in the config file.

So, to fix the problem I had first to put all the .env keys in the config file, and as value I load the .env :

file: config\app.php

[
...
...
   'env' => env('APP_ENV', 'production'),
...
   'x' => env('X', '')
...
]

file: .env.local

APP_ENV=local
X=Y

Then execute

php artisan config:cache

It will produce the file bootstrap\cache\config.php (you can double check that you have the keys and values)

Last thing to do is to substituite all the env('..') that you have in the files out of the config folder.

Upvotes: 0

Emil
Emil

Reputation: 21

To anyone who might come across this issue in the future, the solution was to quite simply write:

  • composer dump-autoload

This actually crashed my install, but after writing

  • composer install

It all worked again. I still have no good answer to why this worked.

Upvotes: 1

Related Questions