Attach and detach In ManyToMany Relationship

Viewed 23

I have an EmployeeSkill model and the table is employee_skills, columns are id, employee_id, skill_id

When creating a user, I can assign multiple skills and I want to assign all skills id for the specific user id in the employee_skills table.

I have the Employees and Skill models.

1 Answers

In many to many relationships between two entities, We have two models and a third table. for more explanation see this and laravel documentation.

you don't need the EmployeeSkill model, delete this, and accord to the laravel recommendation the third table name is better to be singular and in alphabetical order, like this: employee_skill.

Employee model relation:

public function skills()
{
    return $this->belongsToMany(Skill::class);
}

Skil model relation:

public function employees()
{
    return $this->belongsToMany(Employee::class);
}

now when you wanna assign all skills id for a specific employee, you just need to attach or sync:

$employee->skills()->sync({...you skills id...})

// -----

$employee->skills()->attach({...you skills id...})
Related