Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

megaman7's avatar

DB::table vs Model

Are there any advantages to using the DB::table syntax over the Model syntax ie

is DB::table->where('status','active')->first(); better in any way than Model::where('status','active')->first();

If it is why bother with models at all?

0 likes
4 replies
grenadecx's avatar

Laravels models are using Eloquent, which is an ORM library. With that said, it means you can for example, create relations between tables and in a really easy and powerful utilize it.

For example, a class model could have many teachers relation, and if you want to fetch a class with all the teachers, you could do something like:

$class = Classes::with('teachers')->find($id);

// $class->teachers contains all the teachers on the given class

With the query builder you would need to do something like

$class = DB::table('classes')->find($id);
$teachers = DB::table('teachers')->where('class_id', $class->id)->get();

Now Eloquent relations are only steppingstone, you can do a lot more with models, such as normalizing inputs, scopes, mutators even more.

https://laravel.com/docs/5.6/eloquent

There are probably drawbacks, such as speed. I suggest you just use what makes more sense to you.

Procat's avatar

DB::table are faster due to less overhead, Eloquent makes dealing with relationships and formatting data easier, so it's a convience vs performance decision whichever to use.

I found the following pdf from a quick google that explains it better.

megaman7's avatar

Thanks I use models because thats what i started with

I would have through that anything you want to do to the data such as normalizing inputs, scopes, mutators even more. could be done once a collection has been retrieved.

as long as what you do is not something which a model would do in a SQL query there can be no performance penalty in doing it at this level.

models let you use functions like hasOne, hasMany, BelongsTo, BelongsToMany and HasManyThrough instead of joins which mean you never need to write the same "joining" code twice just because it is used in multiple queries. On the other hand this has some limitations which i can encountered. For example when using HasManyThrough columns in the pivot table cant be accessed and if the related table is more than 2 tables way (ie customer > purchaces > reviews > likes) it its going to be difficult.

OBp's avatar

If you want to without class and Eloquent(DB::table()), then directly connect with MySQL database query follow:

$class = DB::select('SELECT * FROM teachers WHERE class_id = ? ',$id);

Please or to participate in this conversation.