SetConnection doesn't work in a non-static eloquent context


I'm trying to do this (Laravel 4.2) :

In database.php

'default' => '',

In a function

$model = new EloquentModel();
$result = $model->find(1);

I have this error : 'Database [] not configured'.
If I put a wrong connection_name (i.e : 'toto'), I got this error : 'Database [toto] not configured'

Same error with (in EloquentModel.php) :

protected $connection = 'connection_name';

It seems in a non-static context, 'setConnection' and 'connection' property don't work properly. Am I correct ?

p.s : The code above works fine, but it's not the point.

mfrancois replied 3 years ago Solution

Hi catalisio,

It's because the find method create a new instance of query.

	public static function find($id, $columns = array('*'))
		if (is_array($id) && empty($id)) return new Collection;

		$instance = new static;

		return $instance->newQuery()->find($id, $columns);

That why don't use find and use a query like:

$model = new EloquentModel();
$result = $model->where($this->model->getKeyName(),'=',1)->get()->last();
jarektkaczyk replied 3 years ago

@mfrancois You're correct. However, this is the way to query on the instantiated model:

catalisio replied 3 years ago

Thank you @mfrancois and @jarektkaczyk !

Jorge Sousa replied 1 week ago

L 5.6 Thank you @mfrancois and @jarektkaczyk !

Sign in to participate in this thread!

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