Laravel SQLSTATE[HY000] [1049] Unknown database 'previous_db_name' - php

I have this error when i use php artisan migrate in my Laravel project.
[PDOException]
SQLSTATE[HY000] [1049] Unknown database 'previous_db_name'
this is my database.php file :
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'current_db_name'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
],
I saw this error in this question and this question but none of them was not helpful.

It clearly mentions that there's no such database named previous_db_name.
From what it seems the database.php file is not where the variable is from.
Check the .env file in your Laravel installation folder to see if that's the database name that you have wrongly specified.

Please run this command:
php artisan config:cache

php artisan cache:clear
AND
restart your server
I had to kill my server and re-run php artisan serve for my project to register the change of my DB_DATABASE name. I kept getting the error even after clearing the cache because I didn't realize this.

In Laravel 5.x You should define the DB Details in two files
.env file in the project folder
.database.php file inside config folder

If you are using PHP artisan serve just restart it. (just in case someone comes searching as I did).

set your database name in .env file too.

I know, it is super late but for people like me, new in laravel and following tutorial from artisansweb. Note that, migrate will not create your database. Rather, it will just create all the tables. Assuming, you have set up your .env file. Now the important part is create the database and users (if you decided to go with custom users) manually. Then, do the php artisan migrate command
hope that helps.

Try this :
<?php
class Config {
private $host = "localhost";
private $db_name = "db_ahp";
private $username = "root";
private $password = "";
public $conn;
public function getConnection() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}

This might be late but I am just updating in case someone else faces a similar issue. I came across the same error, in my case it happened to be due to a missing database in xampp. i.e I was literally running a migration on an inexisting database in xampp.
Kill your server in case it's running. (Use Ctrl+C on windows.)
Make sure that you created the actual DB in your phpMyAdmin.
Run the following command to clear the cache: php artisan cache:clear
Run php artisan migrate once again.
Everything should be good after this.
Happy coding.

Related

Laravel SQLSTATE[HY000] [1049] Unknown database + PHP artisan migrate

I have setup Laravel before and I have never encountered a Database unknown issue. I am trying to install the default Laravel migration on a new project.
I have already created the database on my server.
I am using MAMP Apache port:80 MYSQL Port: 3306
My env setup looks like this:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=thevinesa
DB_USERNAME=root
DB_PASSWORD=******
When I try to use PHP artisan migrate; I get an error of database unknown
SQLSTATE[HY000] [1049] Unknown database 'thevinesa' (SQL: select * from information_schema.tables where table_schema = thevinesa and table_name = migrations and table_type = 'BASE TABLE') at vendor/laravel/framework/src/Illuminate/Database/Connection.php:703
699▕ // If an exception occurs when attempting to run a query, we'll format the error
700▕ // message to include the bindings with SQL, which will make this exception a
701▕ // lot more helpful to the developer instead of just the database's errors.
702▕ catch (Exception $e) {
703▕ throw new QueryException(
704▕ $query, $this->prepareBindings($bindings), $e
705▕ );
706▕ }
707▕ }
+33 vendor frames
34 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
How can I solve this error
Step 1:
Fire this command inside your project
php artisan optimize:clear
Step 2:
Then start project if in local:
php artisan serve
Database is then connected.
Suggestion from #ThandoHlophe
*
I found the issue, so my ~bash directory had the incorrect $PATH, I updated the $PATH and I was able to sort out the issue
It's an simple error, you still did't created your database in mysql or phpmyadmin named thevinesa
DB_DATABASE=thevinesa
Laravel try to find out the database name thevinesa to connect but they didn't find and database named thevinesa . Try to create database.
Then migrate.
php artisan cache:clear
php artisan config:clear
php artisan migrate
command related to database
migrate:fresh Drop all tables and re-run all migrations
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migratioin
Or
Laravel can't connect to your database.
Go to Storage->logs->laravel.log file you will find your error
or you can use php artisan migrate -v if you are in linux . It will show the error details.
And did you create that database?
Check if you have a file bootstrap\cache\config.php. If so remove it.
I didn't find any pdoException Error but If you changed the
`config->database.php` file
Here is my config->databse.php try to compare these
This code taken from Laravel Framework 7.30.4, It might be different but you can have a basic idea.
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
If you want to check you version
php artisan -v
May be error will happens by artisan. For now this is my artisan from Laravel Framework 7.30.4 and php 7.2 look it if you didn't find anything suspecious, didn't change your artisan file take a copy oe backup. And soon as possible show me your error log.
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);
If you're on a MAC using MAMP, adding this to my .env file worked for me
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Laravel: SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client

after installing a new laravel app 5.7 and trying to migrate I get this error:
Illuminate\Database\QueryException : SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (SQL: select * from information_schema.tables where table_schema = xxx_db and table_name = migrations)
at
C:\xampp\htdocs\xxxxx\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll
format the error 661| // message to include the bindings with SQL,
which will make this exception a 662| // lot more helpful to the
developer instead of just the database's errors. 663| catch (Exception
$e) {
664| throw new QueryException( 665| $query,
$this->prepareBindings($bindings), $e 666| ); 667| } 668|
Exception trace:
1 PDOException::("PDO::__construct(): The server requested
authentication method unknown to the client [caching_sha2_password]")
C:\xampp\htdocs\xxxxx\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
2 PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=xxx_db ",
"root", "**********", [])
C:\xampp\htdocs\xxxxx\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
Please use the argument -v to see more details.
This query solved my problem.
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'root#123';
Enter to your mysql as root and run this query
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY '1234';
You can change 1234 to be your password
Run these commands
php artisan config:clear
php artisan migrate
Note: this worked for me.
Re installed MySQL choosing Legacy Authentication Method as shown in iamge attached SQL Authentication method
Database parameters in .env as follows
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password(if any)
Database parameters in config/database.php
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'database_name'),
'username' => env('DB_USERNAME', 'database_username'),
'password' => env('DB_PASSWORD', 'database_password'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
Run php artisan migrate from the projects terminal
By Providing DB_SOCKET in .env file this issue can be resolved like this :
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=my_db
DB_USERNAME=root
DB_PASSWORD=
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
Please Check Server localhost Port on phpmyadmin and .env file like (3306,3307,8889)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3307
DB_DATABASE=mydb
DB_USERNAME=root
DB_PASSWORD=masterpass
Solution is here with 2 step:
Step 1. You have to edit /etc/mysql/my.cnf file and append this setting in mysqld section:
[mysqld]
default_authentication_plugin= mysql_native_password
Step 2. Then run following mysql command:
CREATE USER 'new_root'#'localhost' IDENTIFIED WITH mysql_native_password BY '123';
GRANT ALL PRIVILEGES ON *.* TO 'new_root'#'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
It is better if you restart your mysql service.
sudo systemctl restart mysql
This problem happens when you have install mysql8 and your code compatible with mysql5
You can run Mysql installer - Community (if you are in windows) and then reconfigure mysql server to use legacy authentication method. it should be solve your problem without pain.
Unfortunetly you changes your mysql user or password. If you user/password changed then go to .env file and change your phpmyadmin user and password. Give your database name
DB_DATABASE=hrms
DB_USERNAME=username
DB_PASSWORD=password
If you are getting through this kind of issue like me, avoid losing your time
My scenario: I had to start an existing Laravel5.1 application on PHP5.6. Docker didn't helped me, so I had to create a virtual machine for that.
This issue happens because of the authentication driver for MySQL. On version 8, it will use caching_sha2_password (and Laravel 5 doesn't know what to do with this.
One way to correct this is to downgrade your MySQL version back to 5.7. I've tried a lot, but my apt crashed after "forcing" it to downloading 5.7. If you want to try, heres a discussion for it.
95% of other discussions on StackOverflow and other forums will say to you just ALTER your MySQL user for the mysql_native_password. For some reason, it DOES NOT work. Even after restarting mysql services and flushing it's privileges, doesn't work. I've tried this kind of solutions for hours.
Luckily we have a hero in THIS discussion and is #Amir Hosseinzadeh. You have to create a new user AFTER changing the MySQL driver configuration. Just follow his/her solution on top and it will work.
Go to your .env file and make sure DB_CONNECTION=mysqland DB connections are correct.

Laravel 5 + PostgreSQL: "Database [postgres] not configured." Error

I'm trying to get started with Laravel + PostgreSQL and been following the database tutorial.
Unfortunately, after updating the database configuration file and running php artisan migrate, the following error appears:
[InvalidArgumentException]
Database [postgres] not configured.
What puzzles me is that I didn't specify the "postgres" database in the configuration, but another database I set through cPanel, say "example_database".
Here's some relevant parts of my /config/database.php configuration:
'default' => env('DB_CONNECTION', 'postgres')
And inside the connections array of the same file:
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'example_database'), // This seems to be ignored
'username' => env('DB_USERNAME', 'example_username'),
'password' => env('DB_PASSWORD', 'example_password'),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public'
],
The actual database credentials I'm using are working perfectly on my SQL Workbench client, so this seems to be a Laravel config problem. Any ideas? I have searched around for at least an hour to no avail.
You have to enter your configuration in the .env file.
The configuration you made will only be loaded if they are not already defined in .env
You need to use pgsql instead of postgres.
DB_CONNECTION=pgsql
DB_HOST=localhost
DB_DATABASE=DB_NAME
DB_USERNAME=USER
DB_PASSWORD=PW
Laravel sometimes caches your configurations. If you run into this problem while everything looks alright try running
php artisan config:cache
I know this is an old question and it already has an answer; however, here is an small explanation why:
If you check your database.php in the config directory, you will see that you have few connections types, including pgsql. So, the key have to match to the DB_CONNECTION in .env file. You can definitely replace pqsql connection key with postgres, and it will work on the same way.
However, I would recommend replacing the value DB_CONNECTION, instead of modifying the config.
DB_CONNECTION=pgsql

Laravel: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory")

I am using schema builder to create a Mysql table. I am using Ubuntu 14.04.
My connection for Mysql in config/database.php is :
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'firstapp'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
And Code for creating table with schema builder on routes.php
Route::get('/', function () {
Schema::create('art', function($newtable)
{
$newtable->increments('id');
$newtable->string('artists');
$newtable->string('title',500);
$newtable->text('discription');
$newtable->date('created');
$newtable->date('exhibition_date');
$newtable->timestamps();
});
return view('welcome');
});
Thanks
As far a as i know , you must create a migration file using
php artisan migrate:make yourtable
Then yo must go to database folder you will find a new migration file created , then you must open it , and fill it with your schema , once you finish , then run migration
php artisan migrate
And that's all you will see your new table created.
Migrations laravel 5
First i was using xampp mysql and this was also started /etc/init.d/mysql from terminal, Since i am using Ubuntu 14.04.
I solved the problem which i posted above then another problem came up Saying SQLSTATE[HY000] [1045] Access denied for user 'homestead'#'localhost' (using password: YES).
I changed the .env file which is placed in the root directory of laravel and i changed the Database Name name and password which i was using for mysql.
It solved that problem too and i am up and running.

Laravel/MySQL database connection

I have an unusual problem with my Laravel 4.2 project connecting to MySQL database. This is my database.php
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database_name',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
)
I use XAMPP for Ubuntu.
First, I've created a database in phpMyAdmin. When I tried to run php artisan migrate, it gave me an error of unknown database 'database_name'. I thought it was silly since I've just created a database in phpMyAdmin. Then I tried creating a database through the command line and tried running the migration again. It worked. Tables were created under the database I specified when I run show tables in the command line. It seems to me that the Laravel project is connected to a different mysql server than the phpMyAdmin. Is that even possible? How can I solve this problem?
I've been trying to solve this for hours but still, no luck. Hope someone can help me with my problem.
I solved the problem by following the solution in the link provided by Bulk. I just have to run sudo /opt/lampp/bin/php artisan migrate instead of the plain php artisan migrate. With this, artisan will use the MySQL version provided by XAMPP.

Categories