I have been practicing laravel
and there is something that does not work for me and I do not finish understanding or reviewing the documentation.
It turns out that I want to call the related objects between tables to be able to get their other data, and when I do it find
with a specific id for an object it works, but when I do it with each
for the entire list it returns the relationships as NULL
.
//Here I return NULL
$articles = Article::orderBy('id','DESC')->paginate(5);
$articles->each(function($articles){
$articles->categorie;
$articles->user;
});
dd($articles);
// But if I try it like this, it returns the relationships well
$articles = Article::find(2);
$articles->categorie;
$articles->user;
dd($articles);
What if you do it with a normal foreach?
It may also be that you are overloading the $articles test variable like this:
Take a look at the "with()" function that will basically save you what you're trying to do
I leave you the official link https://laravel.com/docs/5.4/eloquent-relationships#eager-loading
It is not really
each()
the right option in this case, since it is simply a wrapper to iterate, but it is not the way to obtain the relationships.For that there is Eager Loading , which allows you to load one or several relationships when using Eloquent and before generating the query. The advantage with respect to the second method that you show in the question is that you make a single query with Eager Loading, while with a foreach or calling the collections later without preloading them, it generates additional queries:
In case you need for some reason to load the relations after having made the first query, the best way is with load():
Notice the slight difference in how input parameters should be passed in both methods.