douji7399 2016-11-20 02:33
浏览 66
已采纳

Laravel 5.3,似乎无法配置使用哪个数据库?

I'm new to Laravel, just trying out some tutorials right now. I'm to the point of trying to connect to a database that I have configured (and am connected to that database using both Sequel Pro and the MySQL command line application). I know my database is working. The name of the database is "auth".

I've also configured Laravel to see this database in the /config/database.php file:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'auth'),
        'username' => env('DB_USERNAME', 'homestead'),
        'password' => env('DB_PASSWORD', 'secret'),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

This is the code I'm using to connect to the database and pull out the record that matches id=1:

class Controller extends BaseController {
public function home() {

    $user = \App\User::find(1);
    echo '<pre>', print_r($user), '</pre>';

    return view('home');
}
}

But when I run my application, I see the error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.users' doesn't exist (SQL: select * from users where users.id = 1 limit 1)

But if I actually create the database "homestead" with a table called "users", the code runs just fine.

Where am I missing a configuration option?

  • 写回答

1条回答 默认 最新

  • dongliu5475 2016-11-20 02:50
    关注

    The issue is with config/database.php. env('DB_DATABASE', 'auth') this will first check whether DB_DATABASE is defined in .env file, if not exists only it will use auth database.

    So you can update the .env file or update the config to not to use env variable. Like 'database' => 'auth'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?