Search code examples
phplaravel

saving number field with a value of zero in Laravel 5.5


I have a form that accepts delivery of products which I noticed if I enter 0 in the quantity field it doesn't save in the database even if I add data in the calendar or in Notes field.

enter image description here

I already commented out the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,iin kernel.php still doesn't work.

how can I forced laravel to save my data even if I want to put 0 in quantity? thanks in advance!

update

public function store(Request $request)
{
    $input = $request->all();

    $items = [];

    for ($i = 0; $i <= count($input['order_id']); $i++) {

        if (empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;

        $acceptItem = [
            'order_id'      => $input['order_id'][$i],
            'product_id'    => $input['product_id'][$i],
            'order_item_id' => $input['order_item_id'][$i],
            'delivery_date' => $input['delivery_date'][$i],
            'company_id'    => $input['company_id'][$i],
            // 'stock_in_qty' => intval($input['stock_in_qty'])[$i],
            'stock_in_qty'  => $input['stock_in_qty'][$i],
            // 'stock_out_qty' => $input['stock_out_qty'][$i],
            // 'transfer_to' => $input['transfer_to'][$i],
            'delivery_note' => $input['delivery_note'][$i],
            'user_id'       => $input['user_id'][$i],
        ];
        array_push($items, Warehouse1stocks::create($acceptItem));

        $stockSummary = Warehouse1StockSummaries::firstOrCreate(
            ['product_id' => $input['product_id'][$i]],
            ['qty_in'  => $input['stock_in_qty'][$i],
             'qty_out' => null,
            ]);

        if (!$stockSummary->wasRecentlyCreated) {
            $stockSummary->increment('qty_in', $input['stock_in_qty'][$i]);
        }
    }

    if ($input['rd'] == $input['stock_in_qty'] || $input['rd'] == 0) {
        $order_idAcceptedItem = $acceptItem['order_id'];
        $setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
        if ($setStatus) {
            $setStatus->status_id = 4;
        }
        $setStatus->save();
    } else {
        $order_idAcceptedItem = $acceptItem['order_id'];
        $setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
        if ($setStatus) {
            $setStatus->status_id = 3;
        }
        $setStatus->save();
    }

    return redirect()->route('orders.index');
}

Solution

  • empty() will return true with 0 or '0' which will mean that if you try to change the quantity to 0 the for loop will just continue on to the next loop. If you need to check if the value exists you can instead use isset().

    Changing your first if statement to the following should be all you need:

     if(!isset($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;