mercredi 3 juillet 2019

Transaction in laravel eloquent query with multiple insert queries

Hi I want to know how to use transaction query to rollback if my queries have errors and commit if not. I have queries that use foreach cause of having multiple data. here's what I try.

DB::transaction(function(){
                $receiving = New Table1;
                $receiving->created_on = \Carbon\Carbon::now();
                $receiving->created_by = Auth::user()->id;
                $receiving->received_on = \Carbon\Carbon::parse($request->DateAcquired);
                $receiving->received_by = Auth::user()->id;
                $receiving->checked_on = \Carbon\Carbon::now();
                $receiving->checked_by = Auth::user()->id;
                $receiving->remark = $request->Remarks;
                $receiving->save();

                foreach ($request->data as $data)
                {
                    $asset = New Table2;
                    $asset->category = $data[0];
                    /*$asset->asset_number = $data[1];*/
                    $asset->name = $data[2];
                    $asset->brand = $data[3];
                    $asset->model = $data[4];
                    $asset->ownership_type = $data[5];
                    $asset->serial_number = $data[6];
                    $asset->mac_address = $data[7];
                    $asset->cpu = $data[8];
                    $asset->memory = $data[9];
                    $asset->hard_disk = $data[10];
                    $asset->os = $data[11];
                    $asset->remark = $data[12];
                    $asset->description = $data[13];
                    $asset->date_acquired = \Carbon\Carbon::parse($request->DateAcquired);
                    $asset->receiving_id = $receiving->id;
                    $asset->save();
                }
            });

I also tried using DB::beginTransaction(); but I'm getting error of undefined beginTransaction() function in query builder.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NyGIUu
via IFTTT

Aucun commentaire:

Enregistrer un commentaire