There are two mysql tables 1.seats (id,number), 2.reservedseats(id,seat_id,sceering_id). I show all the seats of a specific sceering as checkboxes in show.blade:
{!!Form::model($screening,['method'=>'post', 'action'=> ['ReserveController@store',$screening->auditorium->id]])!!} <input type="hidden" name="screening_id" value="{{$screening->id}}"> @foreach($seats as $seat) <label class="checkbox-inline"> {!!Form::checkbox('seat_id[]',$seat->id,null)!!} Number: {{$seat->number}} </label> @endforeach <div class='form-group'> {!!Form::submit('Create Post',['class'=>'btn btn-primary '])!!} </div> {!!Form::close()!!}
When I click a checkbox it goes the the seat_id[] array. So I send a hidden input and an array with the seat_ids then I want to store in the reservedseats Mysql table. But in the store controller I have the problem. I’m trying something like:
public function store(Request $request){ $screening_id = $request->screening_id; $seat_ids = $request->seat_id; foreach($seat_ids as $seat_id){ Seatreserved::create($seat_id,$screening_id); } }
So it not working but how can I solve that?
Advertisement
Answer
Try this code
public function store(Request $request) { $screening_id = $request->screening_id; $seat_ids = $request->seat_id; foreach($seat_ids as $seat_id) { Seatreserved::create([ 'seat_id' => $seat_id, 'screening_id' => $screening_id ]); } }
Also you can use
public function store(Request $request) { $screening_id = $request->screening_id; $seat_ids = $request->seat_id; $data = []; foreach($seat_ids as $seat_id) { $data[] = [ 'seat_id' => $seat_id, 'screening_id' => $screening_id ]; } Seatreserved::insert($data); }
That is better way to perform this as it will interact with database for once.