how to insert multiple row data based on checkbox selection in Laravel - mysql

I'm stuck with multiple row insertion in laravel. I keep on getting an error which says:
Trying to access array offset on value of type null.
blade.php file:
<tbody>
#forelse($GIV as $GIV)
<tr>
<td> <input type="checkbox" name="status[{{$GIV->id}}]" id="status" value="Issued" ></td>
<td> <input type="text" class="form-control" id="id" name="item_id[{{$GIV->id}}]" hidden="" value="{{$GIV->id}}">{{$GIV->id}}</td>
<td> <input type="text" class="form-control" id="pr_no" name="pr_no[{{$GIV->id}}]" hidden="" value="{{$GIV->pr_no}}">{{$GIV->pr_no}}</td>
<td> <input type="text" class="form-control" id="dep_name" name="dep_name[{{$GIV->id}}]" hidden="" value="{{$GIV->dep_name}}">{{$GIV->dep_name}}</td>
<td> <input type="hidden" class="form-control" id="item_name" name="item_name[{{$GIV->id}}]" value="{{$GIV->item_name}}">{{$GIV->item_name}}</td>
<td> <input type="text" class="form-control" id="description" name="description[{{$GIV->id}}]" hidden="" value="{{$GIV->description}}" >{{$GIV->description}}</td>
<td> <input type="number" class="form-control" id="item_qty" name="item_qty[{{$GIV->id}}]" hidden="" value="{{$GIV->item_qty}}">{{$GIV->item_qty}}</td>
<td> <input type="text" class="form-control" id="unit_measure" name="unit_measure[{{$GIV->id}}]" hidden="" value="{{$GIV->unit_measure}}">{{$GIV->unit_measure}}</td>
<td> <input type="number" class="form-control" id="authorized_qty" name="authorized_qty[{{$GIV->id}}]" hidden="" value="{{$GIV->authorized_qty}}">{{$GIV->authorized_qty}}</td>
</tr>
#empty
<tr><td colspan="16"><center>No Data Found</center</td></tr>
#endforelse
</tbody>
Controller file:
public function addDataGIV(Request $request)
{
$data =request()->all;
foreach(request()->status as $status) {
DB::table('g_i_v_s')->insert(
[
'item_id' =>$data['item_id'][$status],
'item_name' =>$data['item_name'][$status],
'description' =>$data['description'][$status],
'item_qty' =>$data['item_qty'][$status],
'unit_measure' =>$data['unit_measure'][$status],
'authorized_qty'=>$data['authorized_qty'][$status],
'dep_name' =>$data['dep_name'][$status],
'pr_no' =>$data['pr_no'][$status],
]
);
}
}
When a user selects the checkbox and clicks the submit button, I want only the selected checkbox row including the checkbox value to be stored into the database, without any errors.

You're actually quite close, but you're accessing your Array indices wrong; $status, if defined properly, would be Issued, which is not what you want. Also, request()->all is null, but request()->all() (with the ()) would be an Array of your form input; hence the error when trying to use $data[...][...]; later.
This code should work (Note: you don't need $data at all here):
foreach(request()->input('status', []) as $index => $status) {
DB::table('g_i_v_s')->insert([
'item_id' => request()->input("item_id.{$index}"),
'item_name' => request()->input("item_name.{$index}"),
'description' => request()->input("description.{$index}"),
'item_qty' => request()->input("item_qty.{$index}"),
'unit_measure' => request()->input("unit_measure.{$index}"),
'authorized_qty' => request()->input("authorized_qty.{$index}"),
'dep_name' => request()->input("dep_name.{$index}"),
'pr_no' => request()->input("pr_no.{$index}"),
]);
}
Alternative syntax would be request->input('item_id')[$index], like:
foreach(request()->input('status', []) as $index => $status) {
DB::table('g_i_v_s')->insert([
'item_id' => request()->input('item_id')[$index],
'item_name' => request()->input('item_name')[$index],
'description' => request()->input('description')[$index],
'item_qty' => request()->input('item_qty')[$index],
'unit_measure' => request()->input('unit_measure')[$index],
'authorized_qty' => request()->input('authorized_qty')[$index],
'dep_name' => request()->input('dep_name')[$index],
'pr_no' => request()->input('pr_no')[$index],
]);
}
Basically, when looping over request()->input('status', []), you have access to $index, and $status (which is not referenced, but that's ok). $index will be equivalent to whatever $giv->id is on the front-end, and each field exists as an Array Index with that value, so looping and referencing is super easy.

Related

Failed to store data in laravel 8

I'm making a form so that users can request to create a new account to the admin, but every time I try to send data, it always fails, even though I've checked every part of my code, can anyone help me?
the form code :
<form method="POST" action="{{ url('/request-akun/make-request') }}">
#csrf
<div class="form-group col-md-12">
<label for="name">Nama</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group col-md-12">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" id="email">
</div>
<div class="form-group col-md-12">
<label for="password">Password</label>
<input type="text" name="password" class="form-control"
id="password">
</div>
<div class="form-group col-md-12">
<label for="password_confirm">Konfirmasi Password</label>
<input name="password_confirm" type="text" class="form-control"
id="password">
</div>
<button type="submit" class="btn btn-primary pull-right"
style="margin-right: 15px;">Request</button>
</form>
this is the controller :
public function requestAccount(Request $request){
$request->validate([
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required',
'password_confirm' => 'required'
]);
if ($request->get('password') == $request->get('password_confirm')){
$data = new requestAkun();
$data->name = $request->get('name');
$data->ra_user_id = Auth::id();
$data->ra_instansi_id = Auth::user()->instansiID;
$data->email = $request->get('email');
$data->password = $request->get('password');
$data->status = "pending";
$data->save();
return Redirect::to('/request-akun/request-lists')->with('success','Request Berhasil dikirim');
} else {
return Redirect::to('/request-akun/request-lists')->with('error','Password tidak sama');
}
}
this is the model code:
class requestAkun extends Model
{
use HasFactory, Uuids;
protected $table = 'request_akun';
public $timestamps = true;
protected $fillable = [
'name',
'ra_instansi_id',
'ra_user_id',
'email',
'password',
'status'
];
}
this is the route :
Route::prefix('request-akun')->group(function(){
Route::post('/make-request',[userController::class,'requestAccount'])->name('make-request');
});
Error is you don't have ra_instansi_id input in your form.
Not showing any validation error message in your form so better show errors so you check which validation failed.
3.Instead of checking password match in if condition you can change input name password_confirm to password_confirmation so you can change like below
<input name="password_confirmation" type="text" class="form-control"
id="password_confirmation">
and in your validation
$validator=Validator::make($request->all(),[
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);
dd($validator->errors());

how to modify parameters like (style , class ..) in cakephp input?

in cakephp
echo $this->Form->input('email', array('type' => 'email'));
will render
<div class="input email">
<label for="UserEmail">Email</label>
<input type="email" name="data[User][email]" value="" id="UserEmail" />
how to make this like that
<input type="email" name="data[User][email]" value="" id="UserEmail" class="input_class" style="some:style;" />
Just add a "class" and/or "style" argument to your options array.
echo $this->Form->input('email', array('type' => 'email', 'class' => 'input_class', 'style' => 'some:style' ));
See the the FormHelper documentation for a list of all options.
if you need only input without lable you can also try in this way
echo $this->Form->input('email', array('type' => 'email','div'=>false, 'class' => 'input_class', 'style' => 'some:style' ));

Checkbox form sends zeros to mysql, whether boxes are checked or not

I've setup a checkbox form (each question has only one checkbox). The form is submitting, but it only sends zeros to mysql--whether the box has been checked or not. How can I get the correct values (1 or 0) sent to mysql?
Built in codeigniter/mysql.
FORM
<?php echo form_open('addFoo'); ?>
<input type="checkbox" name="foo1" value="" /> //I tried this w/values incl; still zeros
<input type="checkbox" name="foo2" value="" />
<input type="checkbox" name="foo3" value="" />
<input type="checkbox" name="foo4" value="" />
<?php echo form_submit('submit', 'Save Changes'); ?>
<?php echo form_close(); ?>
CONTROLLER
function addFoo()
{
if ($this->input->post('submit')) {
$id = $this->input->post('id');
$foo1 = $this->input->post('foo1');
$foo2 = $this->input->post('foo2');
$foo3 = $this->input->post('foo3');
$foo4 = $this->input->post ('foo4');
$this->load->model('foo_model');
$this->foo_model->addFoo($id, $foo1, $foo2, $foo3, $foo4);
}
}
MODEL
function addFoo($id, $foo1, $foo2, $foo3, $foo4) {
$data = array(
'id' => $id,
'foo1' => $foo1,
'foo2' => $foo2,
'foo3' => $foo3,
'foo4' => $foo4
);
$this->db->insert('foo_table', $data);
}
<input type="checkbox" name="foo2" value="" /> <-- needs a value. Your DB inserts a zero if it's empty.
I think the issue is likely on your DB end, not the form-end.

Passing checkbox values to mysql database using Codeigniter

I'm using CodeIgniter and mySQL to build a checkbox form. The form contains 4 options; each option has only one checkbox; users can select any combination of the options. I want to do the following:
1 - For each checkbox, use a value of 1 (if unchecked) or 2 (if checked) and pass those values through to the database (each checkbox has its own field). Right now, whether checked or unchecked, the checkboxes are sending a value of 0 through to the database.
2 - Once users update their checkboxes, I'd like to update the database to reflect the new values. Right now, a new row is added for each update to the checkboxes.
What I've got so far is a form that submits the checkbox values to the database, a controller, and a model):
Form
<?php echo form_open('addFoo'); ?>
<input type="checkbox" name="foo1" value="" />
<input type="checkbox" name="foo2" value="" />
<input type="checkbox" name="foo3" value="" />
<input type="checkbox" name="foo4" value="" />
<?php echo form_submit('submit', 'Save Changes'); ?>
<?php echo form_close(); ?>
Controller
function addFoo()
{
if ($this->input->post('submit')) {
$id = $this->input->post('id');
$foo1 = $this->input->post('foo1');
$foo2 = $this->input->post('foo2');
$foo3 = $this->input->post('foo3');
$foo4 = $this->input->post ('foo4');
$this->load->model('foo_model');
$this->foo_model->addFoo($id, $foo1, $foo2, $foo3, $foo4);
}
}
Model
function addFoo($id, $foo1, $foo2, $foo3, $foo4) {
$data = array(
'id' => $id,
'foo1' => $foo1,
'foo2' => $foo2,
'foo3' => $foo3,
'foo4' => $foo4
);
$this->db->insert('foo_table', $data);
}
At your Controller :
if you want to insert new entry for all selected checkbox:
foreach($this->input->post('foo') as $r)
{
$data['fieldname']=$r;
$this->model_name->insert($data);
}
if you want to insert all selected checkbox values in different fields within single entry then,
foreach($this->input->post('foo') as $key=>$val)
{
$data['field'.$key]=$val;
}
$this->model_name->insert($data);
Well in reference to setting the values, a checkbox doesn't send anything if unchecked. To achieve what you want, you have to do this:
<input type="checkbox" name="foo[]" value="1" />
<input type="checkbox" name="foo[]" value="2" />
This will send a value regardless of whether the checkbox is checked or not.
use the different values for each checkbox and get the value of checkbox array and use this in your controller print_r($this->input->post('foo')); it will print the values that are selected by user
use like this
<?php
if (isset($_POST['submit'])){
print_r($_POST['foo']);
}
?>
<form action="" method="POST">
<input type="checkbox" name="foo[]" value="1">1<br>
<input type="checkbox" name="foo[]" value="2">2<br>
<input type="checkbox" name="foo[]" value="3">3<br>
<input type="checkbox" name="foo[]" value="4">4<br>
<input type="submit" value="submit" name="submit">
</form>

Codeigniter Insert Multiple Rows in SQL

I am fresh to Codeigniter. I have a form which looks something like this.
<tr>
<td><input type="text" name="Name[0]" value=""></td>
<td><input type="text" name="Address[0]" value=""><br></td>
<td><input type="text" name="Age[0]" value=""></td>
<td><input type="text" name="Email[0]" value=""></td>
</tr>
<tr>
<td><input type="text" name="Name[1]" value=""></td>
<td><input type="text" name="Address[1]" value=""><br></td>
<td><input type="text" name="Age[1]" value=""></td>
<td><input type="text" name="Email[1]" value=""></td>
</tr>
There may be from 0 to n rows, usually 5 to 10 rows. How do I insert them in SQL? Is this possible with Codeigniter or should I use a native PHP script?
$name=$_POST['Name'];
$address=$_POST['Address'];
$age=$_POST['Age'];
$email=$_POST['Email'];
$count = count($_POST['Name']);
for($i=0; $i<$count; $i++) {
$data = array(
'name' => $name[$i],
'address' => $address[$i],
'age' => $age[$i],
'email' => $email[$i],
);
$this->db->insert('mytable', $data);
}
I did this. It works. But the solution seems inelegant.
kevtrout's answer looks better but is currently throwing a lot of errors.
Is there any way to insert all data at one go?
Multiple insert/ batch insert is now supported by codeigniter. It will firing one query rather than firing too many queries.
$data =array();
for($i=0; $i<$count; $i++) {
$data[$i] = array(
'name' => $name[$i],
'address' => $address[$i],
'age' => $age[$i],
'email' => $email[$i],
);
}
$this->db->insert_batch('mytable', $data);
Make your form like this:
<tr>
<td><input type="text" name="user[0][name]" value=""></td>
<td><input type="text" name="user[0][address]" value=""><br></td>
<td><input type="text" name="user[0][age]" value=""></td>
<td><input type="text" name="user[0][email]" value=""></td>
</tr>
<tr>
<td><input type="text" name="user[1][name]" value=""></td>
<td><input type="text" name="user[1][address]" value=""><br></td>
<td><input type="text" name="user[1][age]" value=""></td>
<td><input type="text" name="user[1][email]" value=""></td>
</tr>
Then you can simply do:
foreach($_POST['user'] as $user)
{
$this->db->insert('mytable', $user);
}
The form you show will create a $_POST array with indexes of name, address, age, and email. Each of these will contain the n number of "rows" your form provides. For example:
array(
'name' => array('First Name','Second Name'),
'address' => array ('First Address','Second Address'),
'age' => array('First Age','Second Age'),
'email' => array('First Email', 'Second Email')
);
You may want to rearrange that array into one where each index of the array is a "person". This will make inserting the information into your database simpler.
//subtract 1 from below to account for the assumed submit button
$number_of_rows = count($_POST)-1;
for($i=0;$i<$number_of_rows;$i++){
$person[]['name'] = $this->input->post('Name')[$i];
$person[]['address'] = $this->input->post('Address')[$i];
$person[]['age'] = $this->input->post('Age')[$i];
$person[]['email'] = $this->input->post('Email')[$i];
}
This will create something like this:
array(
0=>array('First Name','First Address','First Age','First Email'),
1=>array ('Second Name','Second Address','Second Age','Second Email')
);
Now you can use a loop to insert each person into the db.
for($y=0;$y<count($person);$y++){
$this->db->insert('mytable',$person[$y];
}