Ad

Make A Laravel Collection Into Angular Array (octobercms)

I managed to fix a problem but I dont understand why it worked and it seems glitchy, so I wonder if someone could explain me. I wanted to get articles from my article models and retrieve that in angular, and I had a hard time getting the subkeys with "featured_images" from octobercms. I found a workaround, like this, in my laravel controller:

public function test()
{  
    $result = Article::take(4)->get();
    $listarr = array();
    foreach($result as $article) {
        $listarr[] = $article;
        foreach($article->featured_images as $image) {
        }
    }
    return response()->json($listarr);
}

But if I remove the foreach($article->featured_images as $image) { } section I dont get the "featured_images" with $listarr. And just using $result doesnt give me those keys if i return response()->json($result);

This is how i want it: http://pastebin.com/MJvnbrrn

But not like this, without "featured_images": http://pastebin.com/1Xa3n9fD

And i get it how i want it if i do that forreach both on $result as $article and only if i then use foreach($article->featured_images as $image) { }. I think I am confused and that there is a more elegant way to this but multidimentional arrays is hard for me.

Ad

Answer

The foreach call is loading the relationship and therefore including it in the subsequent JSON data. The following call will preload the relationship, using eager loading, and should include it in the same way.

Article::with('featured_images')->take(4)->get();

Alternatively you can use "lazy eager loading"

$result = Article::take(4)->get();
$result->load('featured_images');
Ad
source: stackoverflow.com
Ad