Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Adynnor's avatar

Why isn't sync working correctly for pivot table using many to many

Hey I'm not sure if I'm doing this wrong but I have a many to many relationship and I'm trying to use sync the relationship

using laravel 5.4

Posts.php

class posts extends Model
{
    public function genres(){
        return $this->belongsToMany('App\Genres', 'genres_posts');
    }
}

Genres.php

class genres extends Model
{
    public function posts(){
        return $this->belongsToMany('App\Posts', 'genres_posts');
    }

}

Controller.php

    public function createPosts( Request $r ){
    ...
    ...
    ...

        $post = post::find( 1 ); ;
        $post->genres()->sync(['Comedy', 'Off Topic']);
        ...
    }

genres_posts (pivot table)

|||||||||||||||||||||||||||||||||||||||
|| posts_id || genres_id ||
|||||||||||||||||||||||||||||||||||||||

genres

||||||||||||||||||||||
|| id || name ||
||||||||||||||||||||||

Error

QueryException in Connection.php line 647:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'Comedy' for column 'genres_id' at row 1 (SQL: insert into `genres_posts` (`posts_id`, `genres_id`) values (1, Comedy))

Any ideas? (I feel like I'm missing something so blatantly obvious)

Thanks in advance.

0 likes
1 reply
Adynnor's avatar
Adynnor
OP
Best Answer
Level 1

oops my bad, I should be using ID's rather then a column ('name') for sync

Please or to participate in this conversation.