In laravel 9 I have table pivot table defined :
Schema::create('article_vote', function (Blueprint $table) {
$table->id();
$table->foreignId('article_id')->references('id')->on('articles')->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->foreignId('vote_id')->references('id')->on('votes')->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->unique(['vote_id', 'article_id'], 'article_vote_vote_id_article_id_index');
...
});
and having in both models methods with belongsToMany
I can refer articles of a vote as :
$voteArticles = $vote->articles;
When I want to add some more data I do
$vote->articles()->attach($articleId, $data);
But if in database there are already data with article_id / vote_id I got Duplicate entry error.
In which way I can check that such data in article_vote already exists ?
Thanks!
2
Answers
Use
syncWithoutDetaching
instead ofattach
.You can check like this before calling attach.