Eloquent initialization error


#1

Disclosure: This is my first Slim app

I’ve tried to use Eloquent with Slim 3, but I cant seem to get it work. I’ve installed everything with composer, followed the install guide on the site.

When I try to use my User model (wich extends the Eloquent model) i get a fatal error:
Fatal error: Call to a member function connection() on null in ****\vendor\illuminate\database\Eloquent\Model.php on line 3280

My appConfig looks like this:

$config['db'] = [
	'driver'    => 'mysql',
	'host'      => '****',
	'database'  => '****',
	'username'  => '****',
	'password'  => '****',
	'charset'   => 'utf8',
	'collation' => 'utf8_unicode_ci',
	'prefix'    => '',
];

which i pass to the app according to the documentation:

$app = new \Slim\App(["settings" => $config]);
$container = $app->getContainer();
$container['db'] = function (ContainerInterface $container) {
	$settings = $container->get('database');
	$capsule = new \Illuminate\Database\Capsule\Manager;
	$capsule->addConnection($settings);
	$capsule->setAsGlobal();
	$capsule->bootEloquent();

	return $capsule;
};

My User class looks like this:

class User extends Illuminate\Database\Eloquent\Model {}

I’ve found a workaround on Stackoverflow like so:

use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Capsule\Manager;

class User extends Eloquent {
        public function __construct(Manager $capsule, array $attributes = [])
	{
		parent::__construct($attributes);
	}
}

But if i override the constructor according to the port i get a different error:

_Catchable fatal error: Argument 1 passed to Up\models\User::_construct() must be an instance of Illuminate\Database\Capsule\Manager, none given, called in ****\vendor\illuminate\database\Eloquent\Model.php on line 644 and defined in ****\models\User.php on line 14

I’m stuck now. Please help


#2

I’ve found a solution, but it seems a little out of place. I just had to init Eloquent separetly like so:

$capsule = new Capsule;
$capsule->addConnection($config['db']);
$capsule->setEventDispatcher(new Dispatcher(new Container));
$capsule->bootEloquent();

this way the $container['db'] = function () {} part is excuded, but now everything works


#3

Hello, I am newbie in Slim Framework.

Initialize Eloquent with $app->getContainer()->get(“db”); in your index.php

Regards.


[SOLVED] Use Slim with Eloquent: Call to a member function connection() on null
#4

Thank you very much!!!