John Davidson

php - #Laravel How do I store value with switch-button

0 comments
Message:


I want to store value from switch button but I can't save value when switch off
in my blade.


<input name="serial_status[]" type="checkbox"
data-toggle="switchbutton" checked data-onstyle="success"
data-size="xs" data-onlabel="ใช้งาน" data-offlabel="ไม่ใช้งาน">

In my controller:



if ($product->save()) {
$product->productSerials()->delete();
for ($i = 0; $i < count($request->serial_name); $i++) {
if ($request->get('serial_status')) {
$status = 'active';
} else {
$status = 'inactive';
}
$items[] = [
'product_id' => $product->id,
'serial_name' => $request->serial_name[$i],
'serial_status' => $status,
];

}

ProductSerial::insert($items);


My Answer:
In your controller, you need to check if the switch button is checked or not for each serial entry. You can do this by accessing the 'serial_status' array in the request object and checking if the value is 'on' or not.

Here is an updated version of your controller code:

php
if ($product->save()) {
$product->productSerials()->delete();
$items = [];

for ($i = 0; $i < count($request->serial_name); $i++) {
$status = $request->serial_status[$i] == 'on' ? 'active' : 'inactive';

$items[] = [
'product_id' => $product->id,
'serial_name' => $request->serial_name[$i],
'serial_status' => $status,
];
}

ProductSerial::insert($items);
}


This code will check the status of each switch button and set the 'serial_status' value accordingly before inserting the data into the database.

Rate this post

3 of 5 based on 4317 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us