skip to Main Content

I have a model with a connection parameter to a different database.

class User extends Model
{
    protected $connection = 'main_database';
}

When I save the model the connection is returning to default application connection which is named "mysql".

It only happens if one of model values is changed.

 $user = User::find(1);
 $user->surname = 'changed surname';
 $user->save();
    
 dd($user->getConnectionName()); 

Is it a laravel bug?

2

Answers


  1. Chosen as BEST ANSWER

    Never mind. I had this in Trackable trait and that was a problem.

    public function history()
    {
        return $this->setConnection('mysql')->morphToMany(AdmUser::class, 'trackable')->withPivot(['before', 'after'])->withTimestamps();
    }
    

  2. It’s necessary to refresh the $user variable.

    $user->refresh();

    $user = User::find(1);
    $user->surname = 'changed surname';
    $user->save();
    
    $user->refresh();
        
    dd($user->getConnectionName()); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search