Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent fatal error: argument passed not the right instance

Tags:

php

eloquent

slim

I'm in the process of building an endpoint system in PHP using Slim and Eloquent, as outlined here. When running it in my local dev, the code below fails with what appears to be a Fatal Error based on what the methods are expecting

// Load Eloquent
$connFactory = new \Illuminate\Database\Connectors\ConnectionFactory();
$conn = $connFactory->make($settings);
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
\Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);

The actual error is:

[Wed Aug 13 10:31:44 2014] PHP Catchable fatal error:  Argument 1 passed to
Illuminate\Database\Connectors\ConnectionFactory::__construct() must be an instance 
of Illuminate\Container\Container, none given, called in
/Users/outsider/application/index.php on line 22 and defined in
/Users/outsider/application/vendor/illuminate/database/Illuminate/Database/Connectors/ConnectionFactory.php on line 25

There's not a whole lot of guidestones in the docs about this. Any ideas on the possible cause?

like image 694
Cameron Kilgore Avatar asked Dec 25 '22 05:12

Cameron Kilgore


2 Answers

Thanks to Manolo for pointing out what I was missing. I needed to declare a Container and initialize it:

$container = new Illuminate\Container\Container;
$connFactory = new \Illuminate\Database\Connectors\ConnectionFactory($container);
$conn = $connFactory->make($settings);
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
\Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);
like image 170
Cameron Kilgore Avatar answered Dec 27 '22 21:12

Cameron Kilgore


There is an easier way to use Eloquent outside Laravel. You can use Capsule:

/* Setup Eloquent. */
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;

$capsule = new Capsule;
$capsule->addConnection([
    "driver"    => "mysql",
    "host"      => "localhost",
    "database"  => "example",
    "username"  => "root",
    "password"  => "t00r",
    "charset"   => "utf8",
    "collation" => "utf8_general_ci",
    "prefix"    => ""
]);

$capsule->setEventDispatcher(new Dispatcher(new Container));
$capsule->bootEloquent();
like image 43
Mika Tuupola Avatar answered Dec 27 '22 21:12

Mika Tuupola