I’m using the attach to create many to many relationship.
Article model:
class Article extends Model
{
public function sections()
{
return $this->belongsToMany(Section::class);
}
}
Section Model:
class Section extends Model
{
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
attaching sections to the article
$sections = [4,6,5];
$article->sections()->attach($sections);
the error i’m getting
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘article_id’ cannot be null
INSERT INTO `article_section` (`article_id`, `section_id`) VALUES (?, 5), (?, 6), (?, 7)
I tried to switch between attach
, detach
, and sync
sync
only accepted the first element from the array and returned the same error with this SQL
INSERT INTO `article_section` (`article_id`, `section_id`) VALUES (?, 5), (?, 6), (?, 7)
detach
returned false;
2
Answers
If you are on the
store
method:And if you are on the
update
method:YOU need to add the pivot table name to the belongsToMany relations and the foreign ids in the table