TheJohnny
TheJohnny

Reputation: 368

How to insert record with many belongsTo relations in Laravel Eloquent

I am trying to insert record in Eloquent way.

It is clear in basic cases. For example if I have a Blog with Posts and each post belongs to a User I can do this:

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

But how should I do this if my Post belongs to User, Category and Group at the same time?

My first idea was to do it this way:

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

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

What I am doing now is:

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

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

Could someone point me in the right direction?

Upvotes: 11

Views: 19535

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

You're using associate the wrong way around. You have to call it on the belongsTo relation side not the hasMany.

Try this:

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

Upvotes: 13

Related Questions