I'm new to Laravel and web development in general. I'm using Angular for the front-end and Laravel for the back-end in a simple single-page application. I have a table with checkboxes, and I want to save all the checked rows to my database. Currently, I'm sending an array of objects through my POST request to Laravel, which looks like this:
Array [ {…}, {…} ] 0: Object { timeReal: "19:40:00", type: "Passenger", … }
1: Object { timeReal: "19:50:00", type: "Passenger", … } length: 2 <prototype>: Array []
In Laravel I'm toying with the following trying to find the objects:
public function store(Request $requests)
{
$datas = $requests->all();
$data = $datas[0];
foreach ($data as $request) {
$flight = new Flights;
$flight->id_row_fr = $request->input('flight.identification.row');
$flight->flight_number = $request->input('flight.identification.number');
$flight->airline_iata = $request->input('flight.airline.code.iata');
$flight->airline_icao = $request->input('flight.airline.code.icao');
$flight->save();
}
}
I get either "Call to a member function input() on array" or at some point "Undefined array key 0" if I got too deep with indices. I know ->all()
returns and array, I'm not sure what $requests looks like I believe it an object. When sending an individual row with this it works:
public function store(Request $request)
{
$flight = new Flights;
$flight->id_row_fr = $request->input('flight.identification.row');
$flight->flight_number = $request->input('flight.identification.number');
$flight->airline_iata = $request->input('flight.airline.code.iata');
$flight->airline_icao = $request->input('flight.airline.code.icao');
$flight->save();
}
Any help understanding how to make this work would be greatly appreciated!
You are attempting to run a loop on a single array.
The $data = $datas[0];
says get the first index of indexed array, which is in your case is a single array. Simply iterate this $datas = $requests->all();
So your final version of the code should look like this:
public function store(Request $request)
{
$datas = $request->all();
foreach ($datas as $data) {
$flight = new Flights;
$flight->id_row_fr = $data['flight']['identification']['row'];
$flight->flight_number = $data['flight']['identification']['number'];
$flight->airline_iata = $data['flight']['airline']['code']['iata'];
$flight->airline_icao = $data['flight']['airline']['code']['icao'];
$flight->save();
}
}