Search code examples
laravellaravel-5eloquentlaravel-5.3

Laravel: What's the best way to delete a row in a pivot table?


I have 3 models inside a Laravel application:

  • User
  • Question
  • Alternative

Some model relations:

  1. Question can have many Alternative.
  2. Alternative belongs to one Question

There's a pivot table which stores an answer by an user. It stores the user_id and the alternative_id.

In the pivot table, how can I delete all answers from a specific Question? (I have the question_id)


Solution

  • You can use detach as well sync method but you have to define relationships first in your models e.g

    public class Question extends Model {
        public function alternatives() {
           return $this->hasMany(Alternative::class);
        }
    }
    
    
    public class Alternative extends Model {
        public function users() {
           return $this->belongsToMany(User::class);
        }
    }
    

    and than

    $question = Question::findOrFail('question_id');
    
    $question->alternative()->user()->sync();
    

    or

    $question->alternative()->user()->detach();