Search code examples
phplaravelmany-to-manypivot-table

Laravel: how to store same relation but with different additional column


tables that I have:

users: id, name.
roles: id, name.
role_user: user_id, role_id, company_id.

the main idea is that user can have same roles but in different companies. for example:

user_id | role_id | company_id
______________________________
      1 |       1 |         1
      1 |       1 |         2

when I try sync(), it stores only one row instead of two, because of user_id and role_id in both cases are same. couldn't find solution, maybe it's my bad that I couldn't provide correct sentence to search :)


Solution

  • your main problem is when you try to sync() for other company it's remove the other one

    you can try this

    $user = User::find($user_id);
    // sync a specific company_id 
    $user->roles()->sync([$role_id => ['company_id' => $company_id]]);
    

    the sync() method by default syncing the 2 main keys in your situation is user_id & role_id , But if you need to sync more than that you need to add it as a parameter in brackets

    here same example for your case : sync paivot columns