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

Viewed 17124

I am getting this error while trying to save an object into DB.

SQLSTATE[HY000] [1049] Unknown database 'laravel' (SQL: insert into cards (card_price, active, updated_at, created_at) values (0, 1, 2019-10-10 15:14:43, 2019-10-10 15:14:43))

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cardgame
DB_USERNAME=root
DB_PASSWORD=P@assword1!

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', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_T_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'),
        ]) : [],
    ],

CardController.php

  public function generateCards()
  {
  $card = new Card();
  $card->card_price = 0;
  $card->active = 1;
  $card->save();
  }

Web.php

 Route::get('/generate-cards', 'CardController@generateCards');

Card.php

class Card extends Model
{
 protected  $guarded =[];
}

Migration file

public function up()
{
    Schema::create('cards', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('card_price');
        $table->integer('active');
        $table->timestamps();
    });
}

I've tried clearing cache and also have edited DB_PASSWORD To DB_T_PASSWORD as this corrected a similar issue earlier. Double checked the DB name, passwords etc & also other projects are already running also. I'm not able to figure it out.

5 Answers
  1. Go to your localhost server and drop the database and recreate a new one named cardgame

  2. Go to your laravel project in console and run php artisan config:cache command. That way all your env variables will be used.

  3. Run php artisan:migrate to run your migrations for your database and create your tables.

If you do the above 3 steps in that order you should be fine.

You must clear the cache because your old configuration is in the cache file, just run this command in your terminal for clear cache:

php artisan config:cache

You can solve this problem by 2 simple step.

Step:1 php artisan config:cache

step:2 php artisan migrate

I had the same problem and I solved it following these steps:

1) Stop the server

2) Run php artisan config:clear .This command line will remove bootstrap\cache\config.php file

3) Start the server and It should work fine now

create database in php admin then migrate your database again php artisan migrate , it's work 100%

Related