Model's new instance doesn't carry original connection
Hi,
I've been working for the last 9 months on a Laravel project, I'm using Eloquent for most (if not all) of the database related transactions. I noticed that dealing with multiple connections is much more complex than it should.
For instance, using the Repository pattern, I could be dealing with models using a different connection than the default provided from the database settings. However, whenever I need to get an instance or create it and a new instance has to be created from the original one, for instance:
$myModel->firstOrCreate([...]);
This will create a new instance and that new instance isn't carrying the same connection name as $myModel; therefore, I'm attempting to create a new instance in the wrong database.
I can circumvent this doing:
$myModel->setConnection('The right connection name');
$instance = $myModel->firstOrNew([...]);
if (!$instance->exists) {
$instance->setConnection('The right connection name'); // The connection is not the one I want
} else {
$connection = $instance->getConnectionName(); // oh look! that's the right connection!
}
Could this be fixed by changing \Illuminate\Database\Eloquent\Model::newInstance() to simply carry the connection from $this to $model? What do you think?
Out of curiosity, is the second connection consistent (already configured) or is it determined dynamically? If the connection is already configured and the connection name isn't likely to change, Eloquent model's have a $connection property that can be used for this:
class SomeModel extends Model
{
protected $connection = 'mysql'; // Or whatever it needs to be.
}
The $connection property will persist using methods like firstOrNew.