Laravel Array to string conversion when using sizeof - php

i'm new on laravel, basically when i using codeigniter this code works fine.
The problem is i cannot use this for insert data.
for($count = 0; $count < sizeof($cid); $count++){
inset to table for item 1,
inset to table for item 2,
inset to table for item 3,
}
this is my controller
$request->validate([
'pembelian_kode' => 'required',
'barang_kode' => 'required',
'pembelian_total' => 'required',
'pembelian_qty' => 'required',
'supplier_id' => 'required',
]);
$cid = Input::POST('cid');
$cg = PembelianModel::create($request->all());
if($cg){
for($count = 0; $count < sizeof($cid); $count++){
DB::table('pembelian_details')->insert([
'pembelian_kode' => $request['pembelian_kode'], 'barang_kode' => $request['barang_kode'], 'pd_qty' => $request['pembelian_qty']]
);
}
}
return redirect()->route('pembelians.index')
->with('success','Data berhasil ditambah');
reults error
Array to string conversion (SQL: insert into `pembelian_details` (`pembelian_kode`, `barang_kode`, `pd_qty`) values (PBL1812025877, BRG10181125230, 10))
so i have two tables 1 is 'orders' and also 'order_details'. For the table orders it has been successful in adding data, but for orders details there are still errors.
can someone help me ?

I just modified your script .Hope this will work
Problems:
$request['barang_kode']
Missing index
$request is an object not array
$cid = $request->cid;
$cg = PembelianModel::create($request->all());
if($cg){
for($count = 0; $count < count($cid); $count++){
DB::table('pembelian_details')->insert([
'pembelian_kode' => $request->pembelian_kode[$count],
'barang_kode' => $request->barang_kode[$count],
'pd_qty' => $request->pembelian_qty[$count]
]
);
}
}
return redirect()->route('pembelians.index')
->with('success','Data berhasil ditambah');

Related

Updating multiple data at once in two different table in Laravel 9

I want to update multiple data at once in two different table, lets just call it table1 and table2. On table1 I have 3 columns, id, detail_id, and program_name. On table2 I also have 3 columns, id, age, and detail_program. I can store the data from user input into database using this code
$detailId = [];
foreach($request['age'] as $key => $ages) {
$programDetails = ProgramDetail::create([
'age' => $ages,
'detail_program' => $request['detail_program'][$key]
]);
$detailId[] = $programDetails->id;
}
$detailId_string = implode(',', $detailId);
ProgramVaksin::create([
'detail_id' => $detailId_string,
'program_name' => $request->program_name
]);
But when I try to update the data, It can update and return success message, but the data is not what user inputting. For example, user want to change the age data that has detail_id 20,30, and 40 from 1, 2, 3 become 3, 4, 5. After the user click the update button, the age data that user inputting it's become random. Like it should be 3, 4, 5 but it's become 5, 4, 4 or 4, 5, 5 or nothing change at all. This is my code for updating data
public function update(Request $request, ProgramVaksin $programVaksin)
{
$age = $request->input('age');
$detail = $request->input('detail_program');
for ($i = 0; $i < count($age); $i++) {
ProgramDetail::where('id', $programVaksin->detail_id[$i])->update([
'age' => $age[$i],
'detail_program' => $detail[$i]
]);
}
ProgramVaksin::where('id', $programVaksin->id)->update([
'program_name' => $request->program_name
]);
return redirect('/dashboard/program-vaksin')->with('success', 'Data has been updated');
}
Can someone help me about this?
If $age is an array, you could make a collection from it and get a random element on each update.
$ages = collect($request->input('age', [])); // if no age is present, at least have an empty array
$detail = $request->input('detail_program');
for ($i = 0; $i < count($ages); $i++) {
ProgramDetail::where('id', $programVaksin->detail_id[$i])->update([
'age' => $ages->random(),
'detail_program' => $detail[$i]
]);
}
If you want to use pure php methods, there's also array_rand
$ages = $request->input('age', []); // if no age is present, at least have an empty array
$detail = $request->input('detail_program');
for ($i = 0; $i < count($ages); $i++) {
ProgramDetail::where('id', $programVaksin->detail_id[$i])->update([
'age' => $ages[array_rand($ages)],
'detail_program' => $detail[$i]
]);
}

Validate Sum up array field from foreach Laravel

Currently I have working foreach array where it collects all tasks and it contains weight for each task.
Here's my working code
foreach ($arr4 as $row4) {
$taskCode = strtoupper(str_random(12));
$insert_data5[] = array(
'projCode' => $projCode,
'taskCode' => $taskCode,
'taskWeight' => $row4['weight'],
'plan_days' => $row4['planned_days'],
'actual_days' => $row4['actual_days'],
'deleted' => 0,
'by_id' => auth()->user()->id,
'updated_by' => auth()->user()->name,
'created_at' => now(),
'updated_at' => now(),
);
}
dd($insert_data5);
OUTPUT
What I'm trying to do is to validate if the sum up of taskWeight of 5 Tasks doesn't reached 100% this will show an error message.
As of now my idea is to use validator but I have no idea how can I calculate the array fields of taskWeight
$validator = Validator::make(
$insert_data5,
[
......
]
);
if($validator->fails()){
return redirect()
->back()
->with(['errors'=>$validator->errors()->all()])
->with('modal',$modal);
}
Fixed my problem
I declare $ttlTaskWeight = 0; outside of foreach
Then as suggested do the sum up inside of the foreach
like this
$ttlTaskWeight += $row4['weight'];
and I did this to validate if it exceeds 100% or not
if($ttlTaskWeight != 100){
return redirect()
->back()
->with(['errors'=> [0=> 'Total Task Weight must be exact 100%']])
->with('modal',$modal);
}
and the output is this

Check record if exist using updateOrCreate and do a math(SUM) if record exist in laravel 5.5

I have a store function that saves array items into my items table and together with that I am trying to check if the product_is is already in my Warehouse1StockSummaries. if still not, I will grab the product_id and its qty, If its there already then I want to ADD the value from the 'stock_in_qty' which is inside the array to the 'qty_in' in my Warehouse1StockSummaries. I hope my explanation make sense to you :)
here's my code.
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i<= count($input['stock_in_qty']); $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_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]
];
$product_id = $input['product_id'][$i];
$qty_in = intval($input['stock_in_qty'][$i]);
// dd($qty_in);
// ADD stock_in_qty TO QTY_IN ????
$stockSummary = Warehouse1StockSummaries::updateOrCreate(
['product_id' => $product_id ],
['qty_in' => $qty_in,
'qty_out' => null
]);
// dd($stockSummary);
array_push($items, Warehouse1stocks::create($acceptItem));
}
return redirect()->route('orders.index');
}
I check and everything is ok the only missing is the part where I need to grab the value from 'stock_in_qty' and add to 'qty_in' if the product id is already found in Warehouse1StockSummaries. Thank you so much in advance!
You could use the wasRecentlyCreated property on the model to determine if the model has just been created or not. If it hasn't then it won't have used $qty_in value, this means you could then use the increment() to add to the existing value in the database:
$stockSummary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $product_id ],
['qty_in' => $qty_in, 'qty_out' => null]
);
if (!$stockSummary->wasRecentlyCreated) {
$stockSummary->increment('qty_in', $qty_in);
}

decrease the stock when the transaction is completed codeigniter

i want to decrease stock product when transactions is complete, I try with foreach from data but the stock is not decreased correctly
CONTROLLER :
for ($i=0; $i < $count ; $i++) {
//SAVE DETAIL PENJUALAN
$data[] = array(
'nonota' => $this->input->post('nonota',TRUE),
'id_brg' => $this->input->post('kd_brg',TRUE)[$i],
'nama_brg' => $this->input->post('nama',TRUE)[$i],
'jml_brg' => $this->input->post('jml',TRUE)[$i],
'harga_brg' => $this->input->post('harga',TRUE)[$i],
);
//DELETE CART
$cart[] = array(
'rowid' => $this->input->post('rowid',TRUE)[$i],
'qty' => 0
);
$update[] = array(
'id' => $this->input->post('kd_brg',TRUE)[$i],
'stok' => 'stok' - $this->input->post('jml',TRUE)[$i]
);
$this->M_penjualan->updatestock($update,'tbl_barang');
}
MODEL
function updatestock($update) {
$this->db->update_batch('tbl_barang',$update,'id');
}
1.Maybe products ids are not the same as the ones you get from the iteration.
2.Take a look at this line:
'stok' => 'stok' - $this->input->post('jml',TRUE)[$i]
You change value of a string, because 'stok' is a string. It would be something else if you would make $stok - $this->input... .Of course if stock represents some number.
3.Also I would first try to update with simple update. $this->db->set('stok', 'stok-'.$stok, false); - somewhere in your model function.

Error in getting the last inserted ID of a query using batch insert in CodeIgniter

How can I get the last inserted ID of a query using the batch insert in CodeIgniter. I used the code $this->db->insert_id() but it returns the ID of my first inserted array. I can't get the last insert.
Here's what I did:
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders[] = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
}
$this->db->insert_batch('po_order', $orders);
echo $this->db->insert_id(); //will return the first insert array
I can't spot where's my error. My last option is to get it using a query. I also did mysql_insert_id() but always returns to 0.
I think the best way would be to use the batch insert instead of individual inserts in a loop for performance , but to get the last insert id, ADD the First Insert ID & the Affected Rows.
$this->db->insert_batch('po_order', $orders);
$total_affected_rows = $this->db->affected_rows();
$first_insert_id = $this->db->insert_id();
$last_id = ($first_insert_id + $total_affected_rows - 1);
You will need to do something like this,
$insertIds = array();
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
$this->db->insert('po_order', $orders);
$insertIds[$x] = $this->db->insert_id(); //will return the first insert array
}
print_r($insertIds); //print all insert ids

Categories