Can anyone help me on how to save many to many relationship? I have tasks, user can have many tasks and task can have many users (many to many), What I want to achieve is that in update form admin can assign multiple users to specific task. This is done through html multiple select input
name="taskParticipants[]"
The catch here is that through the same form (input) you can add/remove users, that's why I have to use sync().
Maybe I should start from the beginning but don't know where to start…
This is my User model:
public function tasks()
{
return $this->belongsToMany('Task','user_tasks');
}
Task model
public function taskParticipants()
{
return $this->belongsToMany('User','user_tasks');
}
TaskController
public function update($task_id)
{
if (Input::has('taskParticipants'))
{
foreach(Input::get('taskParticipants') as $worker)
{
$task2 = $task->taskParticipants->toArray();
$task2 = array_add($task2,$task_id,$worker);
$task->taskParticipants()->sync(array($task2));
}
}
}
This is structure of tables
tasks
id|title|deadline
user_tasks
id|task_id|user_id
Best Answer
tldr; Use
sync
with 2nd paramfalse
Many-to-many relationship is
belongsToMany
on both models:In order to add new relation use
attach
orsync
.Difference between the two is:
1
attach
will add new row on the pivot table without checking if it's already there. It's good when you have additional data linked to that relation, for example:User
andExam
linked with pivot tableattempts: id, user_id, exam_id, score
I suppose this is not what you need in your situation:
2
sync
on the other hand, will either remove all relations and set them up anew:or it will setup new relations without detaching previous AND without adding duplicates: