Cudos
Cudos

Reputation: 5874

Laravel: Add nested properties to collections

In this example a have one blog that have multiple posts.

How can I add elements to a collection and keep everything a collection:

$post = collect(['title' => 'Hello', 'content' => 'world']);
$blog->posts->push($post);

And then access it with $blog->posts but instead I have to access it with $blog['posts'].

I have tried:

// First way
$blog = collect(['posts']);
$blog->posts->push($post);

// Second way
$blog = collect();
$blog->put('posts' [$post]);

// Third way
$blog = collect();
$blog->put('posts', collect([]));
$blog->posts->push($post);

Upvotes: 0

Views: 318

Answers (1)

Taha
Taha

Reputation: 61

I think you want to append new Article to the blog's articles.

In this case you have to do the following, in the below example:


    $blog = Blog::find(1);

    dump($blog->articles); // Two items retrieved


    // New article
    $newArticle = new Article([
        'title' => 'Article Three',
        'content' => 'Article Three',
    ]);


    // Prepend to articles as a collection
    $blog->articles->prepend($newArticle);
    
    // Save it into DB [If you want]
    // $blog->articles()->save($newArticle);

    dd($blog->articles); // The collection updated with the new item.

Upvotes: 1

Related Questions