Each returns null in relations laravel 5.4

2

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 get their other data, and when I do it with find with a specific id for an object it works, but when I do it with each for the whole list I 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 that way, it returns relationships well

$articles = Article::find(2);
$articles->categorie;
$articles->user;    
dd($articles);
    
asked by César Alejandro M 21.07.2017 в 06:44
source

3 answers

0

Actually each() is not the appropriate option in this case, because it is simply a wrapper to iterate, but it is not the way to obtain relationships.

For that there is Eager Loading , which allows you to load one or several relationships at the moment to use 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 call the collections afterwards without preloading them, it generates additional queries:

$articles = Article::with(['categorie', 'user'])->orderBy('id','DESC')->paginate(5);

In case you need to load the relationships for some reason after having made the first query, the best way is to load ():

$articles = Article::orderBy('id','DESC')->paginate(5);

$articles->load('categorie', 'user');

Note the small difference how the input parameters should be passed in both methods.

    
answered by 21.07.2017 / 15:40
source
0

What if you do it with a normal foreach?

$articles = Article::orderBy('id','DESC')->paginate(5);
foreach($articles as $article){
    $article->categorie;
    $article->user;
});
dd($articles);

It may also be that you are overloading the variable $ articles test like this:

$articles = Article::orderBy('id','DESC')->paginate(5);
$articles->each(function($article){
    $article->categorie;
    $article->user;
});
dd($articles);
    
answered by 21.07.2017 в 09:02
0

Look at the "with ()" function that basically will save you what you're trying to do

$articles = Article::with('categorie')->with('user')->orderBy('id','DESC')->paginate(5);

I leave you official link link

    
answered by 21.07.2017 в 11:54