Skip to content
Advertisement

Problems specifying Laravel Eloquent database at runtime

Laravel 5.8. I am trying to save an Eloquent model, choosing the database connection at runtime:

$catModel = new Cat;
if (env('USE_STAGING')) {
    $catModel->setConnection('staging');
}
$cat = $catModel::create(['name' => $request->name]);

My config/database.php file:

'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
    'mysql' => [
        'driver' => 'mysql',
        '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' => '',
        'strict' => true,
        'engine' => null,
    ],
    'staging' => [
        'driver' => 'mysql',
        'host' => env('STAGING_DB_HOST', '127.0.0.1'),
        'port' => env('STAGING_DB_PORT', '3306'),
        'database' => env('STAGING_DB_DATABASE', 'forge'),
        'username' => env('STAGING_DB_USERNAME', 'forge'),
        'password' => env('STAGING_DB_PASSWORD', ''),
        'unix_socket' => env('STAGING_DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
],

My problem is that each time I run this code, the cat is created in the mysql (default) database, rather than the staging database, even when USE_STAGING is true.

Advertisement

Answer

The problem is the static call of the create() method.

By changing $catModel::create() to $catModel->create() it should use the correct connection:

$catModel = new Cat;

if (env('USE_STAGING')) {
    $catModel->setConnection('staging');
}

$cat = $catModel->create(['name' => $request->name]);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement