skip to Main Content

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


  1. Use syncWithoutDetaching instead of attach.

    $vote->articles()->syncWithoutDetaching([$articleId => $data]);
    
    Login or Signup to reply.
  2. You can check like this before calling attach.

    if (!$vote->articles()->where('article_id', $articleId)->exists()) {
        $vote->articles()->attach($articleId, $data);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search