Support the ongoing development of →
Database Eloquent

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.

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


Hope it helps.


@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;

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') ?


Sign in to participate in this thread!


Your banner here too?


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 - All rights reserved.