It can be tedious to check if many-to-many relationships exist before adding or removing them. The sync method provides a convenient way to only let the given ids be left. Anything not in the given ids will be removed.

Table of Contents

    // attach roles 1, 2, 3
    $users->roles()->attach([1, 2, 3]);
    
    // sync roles 1, 5, 7
    $user->roles()->sync([1, 5, 7]);
    
    // the resulting roles are 1, 5, 7
    // 2, 3 were removed automatically
    // 5, 7 were added automatically

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.