Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RAW Eloquent Queries with Slim PHP

Tags:

php

eloquent

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

like image 344
Alfonso Embid-Desmet Avatar asked Apr 07 '15 19:04

Alfonso Embid-Desmet


2 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');
like image 77
lukasgeiter Avatar answered Oct 10 '22 22:10

lukasgeiter


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
like image 45
Nadir Avatar answered Oct 10 '22 22:10

Nadir