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?
As we have defined the hasMany relationship on Brand model which return the related records of Product model, we can define the inverse relationship on the Product model. Open your app/Product. php model file and add a new method called brand() in it which will return the related brand of a product.
Eloquent Relationships is one of the most useful and powerful features of the Laravel Framework. It is one of the reasons why I like Laravel most. Mainly it helps us to fetch or insert data in a very easy and efficient way.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With