How to insert record with many belongsTo relations in Laravel Eloquent
14,581
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);
Author by
TheJohnny
Updated on July 25, 2022Comments
-
TheJohnny almost 2 years
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?
-
TheJohnny over 9 yearsIt makes sense, but I can;t get it working. In my Post model I have a relation "belongsTo" called group(). But when I do $post->group()->associate($group); I get "Undefined property group" error. I will keep working on it and let you know.
-
lukasgeiter over 9 yearsHmm can you update your question with the relationship definitions? Maybe that's the problem.
-
TheJohnny over 9 yearsI think I found out why I am having this issue: stackoverflow.com/questions/25026123/…
-
lukasgeiter over 9 yearsAh yes, you can't do that. If it's
group
is the foreign key I suggest you name itgroup_id
(then you don't even have to define it in the relation since you're following the convention) -
TheJohnny over 9 yearsYup, this was the problem. So your solution was perfect. Thanks a lot Lukas! :)