what is sync() method in laravel ?

This is a really cool way to deal with many-to-many relationships. However, attaching and detaching things could be a little boring sometimes. Let’s try the sync() method:

  $category->books->sync(
    [4, 8, 15, 17, 22, 42]
  );

  $category->books->sync(
    [4, 8, 15, 16, 23, 42]
  );

Confused? Let me explain everything. The sync method automatically synchronizes relationship data, taking an array of IDs. Element after element, it checks if the relationship was previously created or not, and sets (or unsets) them when necessary. Let’s imagine that the pivot table book_category is empty; here’s the first instruction:

  $category->books->sync(
    [4, 8, 15, 17, 22, 42]
  );

This instruction will create a connection between the chosen category and the books with the IDs 4, 8, 15, 17, 22, and 42. However, here’s the second method call:

  $category->books->sync(
    [4, 8, 15, 16, 23, 42]
  );

It checks everything, and calculates a positive difference and a negative one. Books 17 and 22 are no longer in the array. The relationship will be automatically detached. Instead, books 16 and 23 will be added with attach, another really cool utility method that saves you a lot of time!

Recommended :  Database versioning with the migrations system In Laravel

You can obviously add data to the pivot table with the same method used earlier:

  $category->books->sync(
    [4, 8, 15, 16, 23, 42 => ['notes' => 'We either live together.... or die alone.']]
  );

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares