sgt_disco
sgt_disco

Reputation: 173

Laravel - Eloquent sync() insertting same value to every row

So I just learned how to utilize nested iterations to load data from a pivot table. Now I am trying to save the data but I am not able to .

I have a 'new' blade which the customer can create a new 'Order' with many 'products'.

The blade basically just iterates through all available Products. (As far as I can tell, this is how the blade needs to be setup)

new.blade.php

{!! Form::open(['url' => '/orders/store']) !!}
@foreach ($products as $product)

  <h1>{{ $product->name }}</h1>
  <p>{{ $product->description }}</p>

  {{ Form::text('qty', null }}

@endforeach

So this is my attempt at utilizing a nested iteration in order to pass the 'qty' data to the pivot table.

OrderController.php

public function store(Request $request)
{
    $user = Auth::user();
    $user->load("orders.products"); //eager load pivot table

    /*NEW ORDER*/
    $order = new Order;
    $order->user_id = Auth::user()->id;
    $order->save();

    $product_id_array = [];

    /*PIVOT*/
    $products_to_sync_ids = [ 1,2,3,4,5,6,7,8,9 ];
    $sync_data = [];
    for ($i = 0; $i < count($products_to_sync_ids); $i++) {
        $qty = $request->input('qty');
        $sync_data[$products_to_sync_ids[$i]] = ['qty' => $qty];
    }

    $order->products()->sync($sync_data);

The 'Order' saves, but the qty always defaults to the last Products inputted qty.

Upvotes: 0

Views: 514

Answers (1)

Kamal Paliwal
Kamal Paliwal

Reputation: 1301

You are defining text input with same name 'qty' multiple times that's why when you submit the form, it will give you the value of last text field with name 'qty'.

In this case you should define the qty field as an array of like:

{{ Form::text('qty[]', null }}

And while fetching its value you need to iterate it:

$qty = $request->input('qty');
for ($i = 0; $i < count($products_to_sync_ids); $i++) {
    $sync_data[$products_to_sync_ids[$i]] = ['qty' => $qty[$i]];
}

This may help you to achieve what you want.

Upvotes: 2

Related Questions