Tuesday, May 23, 2017

How to update data when its exist, and not create when its not exist, Laravel 5

I have problem in my database query
I had first import 2 entry like this THIS, and the data inserted correctly

wholesaler_id | target | week | total_transaction | rebate | total_voucher

11223344      | 100.000| 1.2017| 50.000          | 2,25    | 0 
11223344      | 100.000| 2.2017| 120.000         | 2,25    | 2700
11223344      | 100.000| 3.2017| 185.000         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 248.000         | 2,25    | 1417,5

but when i import again with additional row enter image description here, its become like this

wholesaler_id | target | week | total_transaction | rebate | total_voucher

11223344      | 100.000| 1.2017| 50.000          | 2,25    | 0 
11223344      | 100.000| 2.2017| 120.000         | 2,25    | 2700
11223344      | 100.000| 3.2017| 185.000         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 248.000         | 2,25    | 1417,5
11223344      | 100.000| 1.2017| 63.100          | 2,25    | 0 
11223344      | 100.000| 2.2017| 142.700         | 2,25    | 2700
11223344      | 100.000| 3.2017| 205.000         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 279.400         | 2,25    | 1417,5

the result i want is like this

wholesaler_id | target | week | total_transaction | rebate | total_voucher

11223344      | 100.000| 1.2017| 63.100          | 2,25    | 0 
11223344      | 100.000| 2.2017| 155.800         | 2,25    | 2700
11223344      | 100.000| 3.2017| 240.800         | 2,25    | 1462,5
11223344      | 100.000| 4.2017| 332.200         | 2,25    | 1417,5

the rebate and total voucher column isnt problem, the main problem is in total_transaction.
this is the code in my Controller function importCsv



    $voucher = Voucher::firstOrCreate(array(
     'wholesaler_id' => $wholesaler_id,
     'target' => $target,
     'week' => $week . '.' . date("Y"),
     'total_transaction' => $sum,
     'rebate' => $wholesaler_type->rebate_percentage,
     'total_voucher' => $total_voucher
     ));



via Faisal Hilmi

Advertisement