0

When I am Try To use A For-loop in my controller in store function to submit a data

 public function store(Request $request)
{
    $tender = new TenderMaster;

    $tender->bid_name = $request->bid_name;
    $tender->bid_year = $request->bid_year;
    $tender->shipping_mode = $request->shipping_mode;
    $tender->start_date = $request->start_date;
    $tender->end_date = $request->end_date;
    $explodeval = explode(",",$request->origin_port);

    $tender->freight_forwarder = $request->freight_forwarder;
    $tender->save();

    for($i=0;$i<=count($explodeval);$i++){
        $tender->airPorts()->attach($explodeval[$i]);
    }

return back();
}
Vivek kalanka
  • 102
  • 1
  • 3
  • 13

1 Answers1

0

Simple arrays start at index 0 and end at index count()-1

$my_array=['foo','bar','baz'];

// > 3
echo count($my_array)

// > 'foo'
echo $my_array[0]

// > 'baz'
echo $my_array[2]

// error
echo $my_array[3]

Try this:

for($i=0; $i<count($explodeval); $i++){
    $tender->airPorts()->attach($explodeval[$i]);
}

Your error is because you used the condition $i <= count(..., which means that if count($array) == 3 you will get a loop that executes 0, 1, 2, 3. That's 4 elements instead of 3.

You don't have 4 elements in the array, and you don't have an index $array[3].

You can try reading up on php documentation: https://www.php.net/manual/en/control-structures.for.php

Qonvex620
  • 3,819
  • 1
  • 8
  • 15