I am trying to set up Illuminate query builder, so I can run queries like "DB::table('table')->where(...)" .. however I can't get it to work.
I downloaded Laravel throught composer (require laravel/laravel). Next I have created a index.php, where I am including composer autoload file. After that, I am trying to call a simple query:
\Illuminate\Support\Facades\DB::table('users')->get();
However it throws exception "Uncaught RuntimeException: A facade root has not been set.". I was not expecting it to work right away, because I didn't specified the database connection. But based on the message of this exception I am not much clever.
I found a solution here on SO to put this before using query builder:
$Capsule = new Capsule;
$Capsule->addConnection(config::get('database'));
$Capsule->setAsGlobal();
$Capsule->bootEloquent();
However the config::get('database')
statement throws the same exception too. Which means I probably have to configure the config somehow too.
I have tried to include Laravel's bootstrap and boot it, but it does not change anything.
$app = require_once '\composer\vendor\laravel\laravel\bootstrap\app.php';
$app->boot();
Then I tried to set Config's facade app by this statement: Config::setFacadeApplication($app)
After that, when I try to call Config::get('database'), it throws other exception Uncaught ReflectionException: Class config does not exist
Now I am out of ideas how to get it working. What am I missing here?
Solved by extending an Application class and defining config and db instances in bootstrap function, like this:
use Illuminate\Config\Repository;
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;
use Illuminate\Foundation\Application;
class LaravelApp extends Application
{
function boot()
{
parent::boot();
$this->instance('config', new Repository(['database' => $this->getDBCfg()]));
$this->instance('db', new DatabaseManager($this, new ConnectionFactory($this)));
}
private function getDBCfg(){
return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'test'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
];
}
}
Client code looks like this:
$laravelApp = new LaravelApp(__DIR__);
$laravelApp->boot();
Config::setFacadeApplication($laravelApp);
var_dump(\Illuminate\Support\Facades\DB::table('test')->get());
Thanks for help in comments