Support the ongoing development of Laravel.io →
Database Eloquent
0

I believe you have to set the configuration for that DB to be the current one when you need to use it. Not sure this works but you would have to do this when using the second connection so you might want to use it as a ModelEvent, trait or wherever fits best for your situation and project structure.

config([
    'database.default' => 'mysql2',
    'database.connections.mysql2.database' => 'second_db',
    'database.connections.mysql2.driver' => $this->getConnection()->getDriverName()
]);

DB::purge('mysql2');
DB::reconnect('mysql2');
Schema::connection('mysql2')->getConnection()->reconnect();

Hope it helps.

0

@sandy15d that sounds frustrating.

The call $unit->setConnection('mysql2'); shouldn't be needed.

And you don't need to reconfigure the connection like @bcryp7 shows.

The code on your model like you have should be enough:

class Unit extends Model {
      protected $connection = 'mysql2'; 
      protected $table = 'unit_master'; 
}

So the creating should be:

$unit = new Unit();
$unit->unit_name = $request->unit_name;
$unit->unit_code = $request->unit_code;
$unit->status = $request->status;
$unit->save();

Or if you use the fillable property

class Unit extends Model {
      protected $connection = 'mysql2'; 
      protected $table = 'unit_master'; 

    protected $fillable = [
        'status ',
        'unit_code ',
        'unit_name ',
    ];
}

$unit = new Unit::create([
    'unit_name' => $request->unit_name,
    'unit_code' => $request->unit_code,
    'status' => $request->status,
]);

Do you get the suspected config values if you dump config('database.connections.mysql2') ?

1

Sign in to participate in this thread!

LoadForge

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.