For a project I'm working on, I'm using the Eloquent ORM standalone, as explained on this page. Everything is working fine, except that I can not use DB::raw in my code. I got the following PHP error:
Fatal error: Class 'DB' not found
That is correct, as I am only using Eloquent from the Laravel framework, not Laravel itself. Is it possible to use something like DB::raw so I can use specific SQL codes? For example where(DB::raw('YEAR(DateField)'),2013)
Well, looking for a solution for ages, asked it on SO, and found an answer elsewhere on the internet.
Model::whereRaw('YEAR(DateField) = 2013')
will do the trick.
edit:
If you want to use DB::raw
in any other part (for example in the select
, you can use the following:
use Illuminate\Database\Query\Expression as raw;
// You can now use "new raw()" instead of DB::raw. For example:
$yourVar = YourModel::select(new raw("count(FieldA) AS FieldACount"),'FieldB')->groupBy('FieldB')->lists(new raw('FieldACount'),'FieldB');
I came here looking how to wrap a self-made database seeder in a transaction.
The function for that is DB::transaction(function(){});
With that said, DB is a facade. According to the Laravel Facade Documentation DB references both DatabaseManager and Connection.
If you are using standalone Eloquent, you'll want to get the connection out of the Capsule object. Code ends up looking something like this:
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
$db = $capsule->getConnection();
$db->transaction(function()
{
// your transaction code here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With