Insert many to many Laravel 5.5

1

I'm doing a data insertion in a form where it contains data from a many to many relationship, my difficulty is to insert into the pivot table more than a reference data , follow below:

  

Aswecansee,Ihavethefollowingarray:

  • selected_server_list
  • value_list_list

Theyhavetheidoffornecedorthatrelatestoprodutoandavalueforeachfornecedor,ifitweretoinsertonlyidreferencia,vithatisdonethisway,example:

$insert=Product::create($data_form);$providers=$insert->providers()->attach(1);

Iwouldliketoknowhowtosendinadditiontoid,thevalueforthisfornecedor,belowasmymodelandasanexamplethedataalreadyinthedatabase:

Model:

publicfunctionproviders(){return$this->belongsToMany(Provider::class)->withPivot(['value','created_at','updated_at']);}

Bank:

  

As per guidelines, I have refactored and came across the following problem:

My new code treble:

$value_providers = array();
foreach ($data_form['lista_fornecedor_valor'] as $key => $value) {
    $value_providers[] = number_format((float)$value, 2, '.', ',');
}

$providers = $insert->providers()->attach($data_form['lista_fornecedor_selecionado'], ['value' => $value_providers]);

I get this error:

Array to string conversion (SQL: insert into 'product_provider' ('created_at', 'product_id', 'provider_id', 'updated_at', 'value') values (2017-10-14 20:50:19, 5782, 1, 2017-10-14 20:50:19, 20.00), (2017-10-14 20:50:19, 5782, 6, 2017-10-14 20:50:19, 20.00))

Another point is that in sql the 2 values are comm to the value of array 1, not sequential:

example:

$value_providers = ['20.00', '15.00']
    
asked by anonymous 14.10.2017 / 21:39

1 answer

1

If your question is insert in the Many to Many relationship in Laravel following the documentation :

$insert = Product::create($data_form);
if ($insert) // foi inserido.
{
    $providers = $insert->providers()->attach(1, ['value' => 9.75]);
}

that is, after informing id , pass an array of additional information to write to that many-to-many table that has additional fields.

Note: The values in the minimum example set form can use the variables.

Reference: Many To Many Relationships

    
15.10.2017 / 00:22