How to insert a record with many attributes to a relationship in Laravel Rloquent

I am trying to insert a record into an Eloquent Path.

This is clear in basic cases. For example, if I have a blog with posts and each post is owned by a user, I can do this:

$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);

      

But how do I do this if my post belongs to a user, category and group at the same time?

My first idea was to do it like this:

$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);
$group->posts()->associate($post);
$cat->posts()->associate($post);

      

But that doesn't work because the group ID and category ID are null when I save it to the DB and this is not allowed.

Now I am doing the following:

$post = new Post;
$post->content = 'Post content';
$post->group = $group->id;
$post->category = $cat->id;
$user->posts()->save($post);

      

But I don't think this is the right way.

Can anyone point me in the right direction?

+3


source to share


1 answer


You are using the associate

wrong path. You have to call it on the belongsTo

not side of the relationship hasMany

.

Try the following:



$post = new Post;
$post->content = 'Post content';
$post->category()->associate($cat);
$post->group()->associate($group);
$user->posts()->save($post);

      

+3


source







All Articles