Home » Php » Use RAW Eloquent Queries with Slim PHP

Use RAW Eloquent Queries with Slim PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am working on a project with SlimPHP and Eloquent.
I am trying to run a RAW SQL query within a Model’s method, like this:

/models/Form.php

<?php
namespace models;

class Form extends \Illuminate\Database\Eloquent\Model {

protected $table = 'forms';

public function getResponses($form_id)
{
    // HERE
    $select = \Illuminate\Support\Facades\DB::select('select 1');
    return 1;
}

}

I am using Capsule to bootstrap the ORM.

The code above gives me:

Fatal error: Call to a member function select() on a non-object in
/vagrant/vendor/illuminate/support/Illuminate/Support/Facades/Facade.php
on line 208

Documentation is of very help in this case, could you shed some light on this?

thanks

How to&Answers:

Read the setup instructions on github closely and make sure you follow them correctly.


With Capsule you should use Illuminate\Database\Capsule\Manager or as DB “Facade”.

$select = \Illuminate\Database\Capsule\Manager::select('select 1');

I usually import it and define an alias:

use Illuminate\Database\Capsule\Manager as DB;

// ...

$select = DB::select('select 1');

Answer:

Plus if you need to do raw query, it may help to call setAsGlobal() after bootEloquent() like this

$capsule->addConnection($sqliteDb);
$capsule->bootEloquent();
$capsule->setAsGlobal();   // <--- this