mercredi 13 février 2019

Update database using foreach in laravel

I want to insert new data in database using API, but first, i want to check the database using $po_transaction, it exist or not, if $po_transaction exist, do updated. But when i am input same data, it changed all data with one value

This is my database, when first insert:

enter image description here

and this is my database, when i am input same data (This the issue):

enter image description here

This is my controller:

public function post_data(Request $request){

        $po_transaction = $request->input('po_transaction');
        $data = $request->input('data');
        $decode_data = json_decode($data);

        if(!$decode_data){
            return response()->json(['message'=>'No Data','success'=>0]);
        }

        $po_id = Produk::where('po_transaction','=', $po_transaction)->first();

        // if po_id exist, update the data
        if ($po_id) {
            foreach ($decode_data as $item => $value) {
                DB::table('produk')
                    ->where('po_transaction', $po_transaction)
                    ->update(['po_transaction'=>$po_transaction, 'nama_produk'=>$value->produk, 'harga_jual'=>$value->price]);
            }

                return response()->json(['message'=>'success, data saved','success'=>1]);


        }else{
            // if po_id not exist, create new
            foreach($decode_data as $item => $value)
            {
                $saveTransaction = new Produk();
                $saveTransaction->po_transaction = $po_transaction;
                $saveTransaction->nama_produk = $value->produk;
                $saveTransaction->harga_jual = $value->price;
                $saveTransaction->save();
            }
            if($saveTransaction->save()){
                return response()->json(['message'=>'success, data saved','success'=>1]);
            }else{
                return response()->json(['message'=>'no data saved','success'=>0]);
            }
        }
    }

and for data, i am using json data like this:

[
  {"produk":"shampoo","price":"12000"},
  {"produk":"noodle","price":"110200"}, 
  {"produk":"cup","price":"1000"}
]

How to fix this issue, when i input same data, it not only change all data with one value?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire