0
votes

Disclosure: This is my first Slim app

I've tried to use Eloquent with Slim 3, but I can't 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 (which 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

1
$capsule->addConnection($container->get('database')); != $capsule->addConnection($config['db']);danopz

1 Answers

1
votes

I've found a solution here, 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 excluded, but now everything works

EDIT (for comments): the whole part now looks like this:

$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;
};*/

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