Sanzeeb Aryal Sanzeeb Aryal - 6 months ago 10
PHP Question

Making id not incrementing during loop

I have this form in the view:

Your Name: <input type="name" name="name" id="name" ><br><br>
Your Contact No. <input type="contact" name="contact" id="contact" ><br><br>
Todays date:<mark>{{$mytime->format('Y-m-d, l')}}</mark><br><br>
<br><br>BOOK SEATS:<br>
@foreach($seats as $seat)
@if($seat->available=='1')
<input type="checkbox" name="check[]" value="{{$seat->book}}" >{{$seat->book}}<br><br>
@else
<input type="checkbox" name="check[]" value="{{$seat->book}}" disabled>{{$seat->book}}<br><BR>
@endif
@endforeach
<button type="submit" class="btn btn-default">Book</button>
</form>


this form redirects to this controller which inserts the name contact and the value of checkbox checked with loop. This way, if i check two values and submit the form, due to for loop two rows will be inserted with same
name
contact
but with different
booked_seats
and
id
(i used id as auto increment). Is there any way of inserting the checked values into booked_seats with only one row. OR making the
id
same for any rows inserted(checked values) at the time.

public function book(Request $request)
{
$name=$request->get('name');
$contact=$request->get('contact');
$check=$request->get('check');
$totalcheckboxchecked=sizeof('$check');
for($i=0;$i<=$totalcheckboxchecked;$i++)
{
if (array_key_exists($i,$check) )
{
$booked=$check[$i];
$book=bus::insert(['name'=>$name,'contact'=>$contact, 'booked_seats'=>$booked, 'active'=>'1']);
seats::where('book',$booked)->update(['available'=>'0']);

}
}
return redirect('/bus')
->with('message','booked successfully!!!');

}

Answer

You can store the checked values in database using serialize

$booked = serialize ($check);

Then you can save in database like this without using for loop

$book=bus::insert(['name'=>$name,'contact'=>$contact, 'booked_seats'=>$booked, 'active'=>'1']);
    seats::where('book',$booked)->update(['available'=>'0']);

To rretrieve the values use unserialize

unserialize($booked);

Here is the full code.

public function book(Request $request)
  {
    $name=$request->get('name');
    $contact=$request->get('contact');
    $check=$request->get('check');
    $checkarray = serialize($check);
    $totalcheckboxchecked=sizeof('$check'); 
for($i=0;$i<=$totalcheckboxchecked;$i++)
{
    if (array_key_exists($i,$check) )
{   
    $booked=$check[$i];

    seats::where('book',$booked)->update(['available'=>'0']);

}
$book=bus::insert(['name'=>$name,'contact'=>$contact, 'booked_seats'=>$checkarray, 'active'=>'1']);
}
        return redirect('/bus')
            ->with('message','booked successfully!!!');

}
Comments