Matt Catellier Matt Catellier - 6 months ago 13
SQL Question

Are Laravel 5.2 queries lazy loaded?

I am working with Laravel 5.2 and the eloquent models to interact with my database and I am wondering when the query is actually sent to the server?

I am developing a search/sort bar where need to build a query based on which values are presented. For example: ("" means no value selected)

Destination->Paris Airport->"" Sort-> ""

So I am building my queries based on if else statements right now. Building many different queries based on which values are filled in. i.e. (Query for above values)

if(Destination != "" && Airport == "" && Sort == "")
Flight::where(['destination']=>Destination)->get();


So I have to do this 9 different times for each of the possible combinations with this approach. What I'm wondering is when is the query actually executed? It seems like it would be when you call ->get() method on the model? Is this how it works? If so I could do something like this, and it would make my life much easier. (psuedo code)

$query = Flight();
if(Destination != "")
$query->where(['destination'=>Destination]
if(Airport != "")
$query->where(['airport'=>Airport])
etc...


Maybe a silly question, but having trouble with the googling.

Thanks,

Matt

Answer

Query will be executed when you call get(), all() or first() methods. If you want to see how many queries Laravel executed per each request and what exactly queries did it build, install debugbar.

Add this to composer.json:

"require-dev": {
    "barryvdh/laravel-debugbar": "^2.2",

And run composer update.

Comments