Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why attach method returns null in Laravel?

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?

like image 826
Hamed Kamrava Avatar asked Mar 12 '23 00:03

Hamed Kamrava


2 Answers

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.

like image 173
revo Avatar answered Mar 14 '23 13:03

revo


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.

like image 21
Talha Malik Avatar answered Mar 14 '23 12:03

Talha Malik