Home > Enterprise >  Laravel Query efficiency difference
Laravel Query efficiency difference

Time:12-03

please could somebody tell me wich one is most efficient select in laravel:

  1. $car = Car::all(); ------- $car = Car::find();
  2. $car = DB::table('car')->get(); ------ $car = DB::table('car')->first();

CodePudding user response:

For me most efficient is selecting from the Model: like Car:all(), but it's always better if you use pagination or just don't take all of the records from the database with all() method.

But selecting with DB is a bit faster and in some cases maybe it would be better to use.

In the end, it always depends on what`s your problem and which way do you want to solve it.

for a better understanding I recommend you to watch this video and after that maybe keep going to search for some more information or just try it out yourself.

https://www.youtube.com/watch?v=uVsY_OXRq5o&t=205s

CodePudding user response:

Your first approach:

$car = Car::all();   ------- $car = Car::find();

Makes use of Eloquent. This means, all the rows received from the query will be hydrated to Model instances, and all of those will be injected into an instance of Collection (for multiple elements, of course). This is useful because you then will have all the benefits that this brings. However, this comes with a little decrease on performance (understandable)

Your second one:

$car = DB::table('car')->get(); ------ $car = DB::table('car')->first();

Uses the Query Builder instead. The results (as a whole) will be also casted into an instance of Collection, but its items will be simple arrays. This means that the process will be faster (more performant) but on detriment of not having all the cool features of Eloquent.

There's even a more performant option: Using raw queries. That also has tradeoffs: Results are not hydrated into a Collection instance.

Which one to use? It depends on your needs. Usually I go for the Eloquent option. I use the Query Builder directly when I need to make queries to big databases and need speed.

  • Related