laravel [1049] Unknown database

Viewed 7117

I am new to laravel and I am currently having issues when I try to view my database through a controller. When I try to use a controller to view my data I get the following error.

"SQLSTATE[HY000] [1049] Unknown database 'laravel'".

If I use artisan tinker I can do an ::all() and view my data, I have also successfully migrated my data over as well. It just for some reason does not seem to like my views.

I have viewed other similar answers which suggested to run

php artisan cache:clear.

This however did not do anything for me.

controller:

class authorsController extends Controller
{

    public function index(){
        $authorList = \App\Author::all();
        //return $authors;
        return view('library.authors');
    }
}

Inside .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=library
DB_USERNAME=root
DB_PASSWORD=
4 Answers

If you are running Laravel with php artisan serve, it's won't pick up .env changes until you stop and restart the server.

It's possible you had "laravel" set as your DB name when the server was started. Kill it and then run the command again.

Try this list of commands

php artisan cache:clear
php artisan view:clear
php artisan route:clear
php artisan clear-compiled
php artisan config:cache

After put this code in your route web.php and run in the browser this will give you a database is connected or not.

Route::get('/testConnection', function () {
try {
      DB::connection()->getPdo();
      if(DB::connection()->getDatabaseName()){
          echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
          die;
      }else{
          die("Could not find the database. Please check your configuration.");
      }
  } catch (\Exception $e) {
      die($e->GetMessage());
  }
});

Hope this will help you.

I am not sure as to why still, but I did find a fix that worked for me. Inside the config.database.php I changed 'database' => env('DB_DATABASE', 'forge') to 'database' => env('library', 'library'). I feel that I should not have to change those, but for what ever reason that corrected the issue.

It leads me to think that it had something to do with the .env file but not sure. I will have to start a new project to verify that it is not something weird on my system.

I tried php artisan config:clear. I tried php artisan cache:clear. I had the database created. I dropped it and re-created it a few times. I even tried using an existing database by changing the DB_DATABASE value in .env I could connect to the new and existing databases via CLI. I saw the drivers in php -m. So to fix this on Windows 10 was change DB_HOST=127.0.0.1 to DB_HOST=localhost in .env and cleared out config/cache again. Worked.

Related