Skip to content
Advertisement

Laravel store multiple just saves one

I am sending array of data to controller but it only saves 1 row to database, I need to save multiple rows (depend on array length).

Code

controller

public function store(Request $request)
{
    $user = Auth::guard('api')->user();

    $transit = new Transit;
    foreach($request->input('serials') as $serial){ //looping my serials array for each row
        if(!empty($serial['barcode_id'])) { // filter out empty objects from array
            $barcode = Barcode::where('serial_number', $serial['barcode_id'])->orWhere('u_serial_number', $serial['barcode_id'])->first();
            $transit->barcode_id = $barcode['id'];
            $transit->transNu = mt_rand(1000000000, 9999999999);
        }
    }
    $transit->from_id = $request->input('from_id');
    $transit->to_id = $request->input('to_id');
    $transit->sender_id = $user->id;
    $transit->description = $request->input('description');
    if($transit->save()){
        DB::table('outlet_products')->where('barcode_id', $transit->barcode_id)->update(['outlet_id' => null]);
    }
    return response()->json([
        'data' => $transit,
        'message' => 'Transit data saved successfully.'
    ]);
}

Screenshot

request data

one

stored data

two

any idea?

Advertisement

Answer

Move $transit = new Transit; inside the foreach, and end the foreach loop right before returning the response.

What happens in the current setup is that during the first iteration, a transit object is is created and when it gets saved, it will get an id. So for the second/and subsequent iterations, the Transit object will have an id and calling save will perform an update operation on the record with that id.

Moving it inside foreach will always give you a new empty Transit object and saving will give you a new record.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement