Eloquent relations - attach (but don't save) to Has Many Eloquent relations - attach (but don't save) to Has Many laravel laravel

Eloquent relations - attach (but don't save) to Has Many


It sounds like you just want to add the new comment object to the page's comments collection - you can do that easily, using the basic colection add method:

$page = new Page;$comment = new Comment;$page->comments->add($comment);


You can't do since there are no ids to link.

So first you need to save the parent ($page) then save the child model:

// $page is existing model, $comment don't need to be$page->comments()->save($comment); // saves the comment

or the other way around, this time without saving:

// again $page exists, $comment don't need to$comment->page()->associate($page); // doesn't save the comment yet$comment->save();


according to Benubird I just wanted to add something as I stumbled over this today:

You can call the add method on a collection like Benubird stated.To consider the concerns of edpaaz (additional fired query) I did this:

$collection = $page->comments()->getEager(); // Will return the eager collection$collection->add($comment) // Add comment to collection

As far as I can see this will prevent the additional query as we only use the relation-object.

In my case, one of the entities were persistent while the first (in your case page) was not (and to be created). As I had to process a few things and wanted to handle this in a object manner, I wanted to add a persistent entity object to a non persistent. Should work with both non persistent, too though.

Thank you Benubird for pointing me to the right direction. Hope my addition helps someone as it did for me.

Please have in mind that this is my first stackoverflow post, so please leave your feedback with a bit concern.