I have 3 tables posts
,tags
, and a pivot table post_tag
.
post_tag
table is :
+----+-------------+--------+
| id | post_id | tag_id |
+----+-------------+--------+
| 1 | 1 | 2 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 4 | 3 |
| 6 | 5 | 3 |
+----+-------------+--------+
I have this in Post
model :
class Post extends Model {
public function tags() {
return $this->belongsToMany('Tag');
}
}
And this in Tag
model :
class Tag extends Model {
public function posts() {
return $this->belongsToMany('Post');
}
}
Now in my Controller I'm trying to insert a record to the pivot table post_tag
:
$post = Post::find(4);
$post_tag = $post->tags()->attach(2);
return $post_tag //it returns null
So, I need to get details of created record in pivot table, but $post_tag
contains null
!
How can I get the details(like id ,...
) of last inserted record on the pivot table?
You may want to check sync()
method which returns an array of attached ids as well:
$post = Post::find(4);
$post_tag = $post->tags()->sync([2], false);
var_dump($post_tag['attached']);
Output:
array(1) {
[0]=>
int(2)
}
Be aware that a false
parameter should be passed as the second argument to avoid detaching all other rows.
The attach method doesn't return any thing, this is why you are getting null. To check if record was inserted successfully you would need to make another call to DB. It is similar to Delete method. Check this for reference to attach method.
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