csow
csow

Reputation: 47

How to store array in Laravel?

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?

Upvotes: 2

Views: 40580

Answers (3)

vivek thummar
vivek thummar

Reputation: 1

    $input = $request->all();
        
    $invoice = Invoice::create($input);
    
    foreach($input['products'] as $key => $value){            
        $product['product_id'] = $value['product_id'];
        $product['amount'] = $value['amount']; 
        $product['invoice_id'] = $invoice->id;
        InvoiceProducts::create($product);
    }

    return redirect()->route('invoices.index')->with('success', 'Invoice Added Successfully');

}

Upvotes: 0

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

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.

Upvotes: 6

JPark
JPark

Reputation: 789

You can also create a new instance of your model to store values.

Example:

foreach($seat_ids as $seat_id) {
    $reserved = new Seatreserved();

    $reserved->seat_id = $seat_id;
    $reserved->screening_id = $screening_id;

    $reserved->save();
}

Upvotes: 0

Related Questions