Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the different between "with" and "load" in laravel

Tags:

php

laravel

I have go through the laravel documentation, I didn't get the different between With or Load in queries, In which condition we need to use With or Load? Please describe it

Model::find(1)->with('firstModel','SecondModel');

Model::find(1)->load('firstModel','SecondModel');
like image 882
Harman Avatar asked Jun 13 '16 05:06

Harman


2 Answers

In a nut shell, with() loads a relationship with parent model at the same time. That's eager load.

If you don't want to eager load that data, you can use lazy load or eager lazy load. In this case data will be loaded when you'll actually start to use relationship. So, you can decide at runtime what exactly relation you want to load or maybe you will not want to load any relationship data at all etc.

like image 107
Alexey Mezenin Avatar answered Oct 20 '22 04:10

Alexey Mezenin


Model::find(1)->with('firstModel','SecondModel');

Isn't really doing anything at all, as with is a new builder now that isn't related to the model returned from find(1).

Model::with(....)->find(1);

Would eager load the relationships.

Model::find(1)->load(...);

Is lazy eager loading. It is loading the relationships to an existing Model instance that you already have retrieved. (as find(1) is returning a Model instance and load is telling it to then load the relationships specified) load can also be used on Collections to load relationships on all the Model instances contained. load is more useful when dealing with a set of Models compared to a single one as just using the dynamic property (lazy loading, if not loaded already) for a relationship on a Model would cause the same queries to be ran. On a set it removes any N+1 issue while iterating through them.

You can check out this article for some more information on this.

asklagbox - blog - Eloquent Querying Relations

like image 20
lagbox Avatar answered Oct 20 '22 05:10

lagbox