Skip to content
Advertisement

Laravel using Eloquent and DB in the same Model

I have a model called Bar which extends Laravel’s Eloquent

class Bar extends Eloquent{

}

Now the problem is that I need to make some joins between multiple tables and for that I’d like to use the DB class from Laravel to improve performance(using eloquent ends up costing me around 750 queries and 20 seconds to load).

Can i use DB in the same model that extends Eloquent?

If not, should i create another model?

Advertisement

Answer

Your models should extends IlluminateDatabaseEloquentModel not Eloquent

Eloquent is basically the ORM laravel uses by default

use IlluminateDatabaseEloquentModel;

class Bar extends Model
{
    public function getFooAttribute()
    {
        return DB::table('bars')->value('foo');
    }
}

You can use the DB facade almost anywhere to perform Query Builder SQL statements just fine

Hope this helps

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement