How to use "Sync" from Laravel 5.1?

Asked

Viewed 1,739 times

1

I recently discovered a feature of eloquent called sync, I saw that he kind of compares the data passed with the data that’s in the database and deletes or inserts what’s different. I wanted to implement this in my application, but I didn’t understand how.

I have the following table:

id  id_setor_empresa  id_exame
1   5                 3
2   5                 20
3   5                 17

Which stores which exams should be done by employees of a sector.

Currently when an edition is made, I delete all the sector exams and register the new ones. How can I use the sync to do this more "clean"?

1 answer

2


The method sync() is available since version 4, and is used only in many to many relations (belongsToMany).

This method is similar to attach(), follows explanation:

attach():

Used to add a new relation in the dynamic table.

Example:

$setor = Setor::find(5);
$setor->exames()->attach(2);

Your table would now look like this:

id  id_setor_empresa  id_exame
1   5                 3
2   5                 20
3   5                 17
4   5                 2

Sync():

Used to replace existing data with data reported via parameter.

Example:

$setor = Setor::find(5);
$setor->exames()->sync([20,10]);

Your table would now look like this:

id  id_setor_empresa  id_exame
2   5                 20
4   5                 10

In this case the data that is not in the array is deleted and inserts those that are not yet in the table.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.