Add your array in the loop and get JSON.
$cars = Car::all();
foreach ($cars as $car) {
$car->type = [["model" => "320", "year" => "2012"], ["model" => "530", "year" => "2013"]];
dd($car->toJson());
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I wish to add an array to an JSON object inside an JSON array (I am new to this so might have wrong terminology here).
In my controller I have the following query to fetch all cars: $cars = Car::get();
return $cars; would give currently only one car [ { "id": "1", "manuf":"BMW", "created_at": "2015-01-23 19:12:05", "updated_at": "2015-01-25 07:59:08" } ]
Next I wish to loop through each car and inside the loop I need to add an array
foreach ($cars as $car) {
What do I need to do to add an array to the JSON object car? so that it would look like this
[ { "id": "1", "manuf":"BMW", "type":[{"model":"320","year":"2012"},{"model":"530","year":"2013"},],"created_at": "2015-01-23 19:12:05","updated_at": "2015-01-25 07:59:08"}] }
Add your array in the loop and get JSON.
$cars = Car::all();
foreach ($cars as $car) {
$car->type = [["model" => "320", "year" => "2012"], ["model" => "530", "year" => "2013"]];
dd($car->toJson());
}
Please or to participate in this conversation.