How to use the "sync" of Laravel 5.1?

1

Recently I discovered a feature of eloquent called sync , vi that it sort of compares the data passed with the data that is in the database and deletes or inserts what has different. I wanted to implement this in my application, but I did not understand how I would do it.

I have the following table:

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

That stores which exams should be done by employees in an industry.

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

    
asked by anonymous 25.01.2016 / 14:24

1 answer

2

The method sync() has been available since version 4, and is used only in many-to-many relationships (% with%).

This method is similar to belongsToMany , below explanation:

attach ():

Used to add a new relationship in the PivotTable.

Example:

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

Your table now looks like this:

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

sync ():

Used to replace the existing data with those entered via parameter.

Example:

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

Your table now looks 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 the data that is not already in the table.

    
25.01.2016 / 15:08