Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Laravel Eloquent - Attach vs Sync

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.69k
    Comment on it

    Attach and Sync are the two methods which we used in our Laravel Eloquent. We can describe this as follow:

    attach():

    1) This is used for Insert related models. This method is used when we want to work with many-to-many relations.
    2) When we are using attach() then we expect "No array parameter".

    Example:

    $user = User::find(1);
    
    $user->roles()->attach(1);
    

    sync(): It is similar to attach(). The main difference between sync() and attach() is:

    1) Sync method accepts an array of IDs to place on the pivot table.
    2) Secondly, most important, The sync method will delete the models from table if model does not exist in array and insert new items to the pivot table.

    Example:

    userRole

    id  userId roleId
    1    2       1
    2    2       5
    3    2       2
    


    The example of sync is:

    $user->roles()->sync(array(1, 2, 3));
    

    This operation will delete

    id  userId roleId
    2    2       5
    

    And insert roleId 3 to the table.

    userRole table

    id  userId roleId
    1    2       1
    3    2       2
    4    2       3
    

    This is the main difference between attach() and sync().

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: