Wolrab Wolrab - 22 days ago 8
PHP Question

Laravel Eloquent Controller Match

I have a table which contains details of an order


  • ID

  • Order No

  • Stock Code

  • Quantity to Deliver



I'm outputting in my view an order and doing a foreach on the items.

This results in a page which allows us to despatch a quantity of our choice.

My question is how do I pass the quantity which may have changed from the order to the controller to update?

For example.

<form>
@foreach($order->items as $item)
{{ $item->stk_code }}<br>
<input name="{{ $item->id }}" value="{{ $item->ordered }}">
@endforeach

<button type="submit">Send Items</button>
</form>


My controller (just an idea)

public function processDespatch(Request $request, $id)
{

$order = Order::where('OH_ORDER_NUMBER',$id)->first();


foreach($order->items as $item){

if($item->id = "$request ? ID"){

PERFORM UPDATE COMMAND IN TABLE

}

}
}


You'll see above I've used the phrase "$request ? ID" here I'm struggling how I can link the result?

Hopefully somebody can help

Answer

In your blade file your foreach should be as:

@foreach($order->items as $item)
    {{ $item->stk_code }}<br>
    <input name="items[{{ $item->id }}]" value="{{ $item->ordered }}">
@endforeach

Then your controller function shoud be as:

public function processDespatch(Request $request, $id)
{
    $order = Order::where('OH_ORDER_NUMBER',$id)->first();

    $input_items = $request->items; // it will return an array

    foreach($order->items as $item) {
        if (array_key_exists($item->id, $input_items)) {
            $item->update( ['ordered' => $input_items[$item->id]] );
        }
    }
}
Comments