11

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
  • 370
  • 1
  • 5
  • 17

1 Answers1

13

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);
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • It 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. – TheJohnny Jan 04 '15 at 16:09
  • Hmm can you update your question with the relationship definitions? Maybe that's the problem. – lukasgeiter Jan 04 '15 at 16:13
  • I think I found out why I am having this issue: http://stackoverflow.com/questions/25026123/laravel-belongs-to-throwing-undefined-error – TheJohnny Jan 04 '15 at 16:23
  • Ah yes, you can't do that. If it's `group` is the foreign key I suggest you name it `group_id` (then you don't even have to define it in the relation since you're following the convention) – lukasgeiter Jan 04 '15 at 16:25
  • Yup, this was the problem. So your solution was perfect. Thanks a lot Lukas! :) – TheJohnny Jan 04 '15 at 16:29