I'm learning Laravel and i'm creating a simple app. In that app i want to get query of objects which depends on value of select element in view. I came up with this JS code:
$('#carClass').change(function(){
var classID = $('#carClass option:selected').val();
var gameID = $('#gameID').val();
axios.post('/getcars', {
game_id: gameID,
carClassID: classID
}).then((r)=>{
var cars = r.data.carsQuery;
console.log(cars);
console.log(cars.lenght);
for(var i=0; i<cars.length; i++){
$('#chooseCar').append('<option>' + cars[i].car + '</option>');
}
});
});
and in controller i created this function:
class CarController extends Controller
{
public function getCars(Request $request)
{
$query = Game::find($request->game_id)->cars->where('car_class_id', $request->carClassID)->sortBy('id');
return Response([
'carsQuery' => $query->toArray()
]);
}
}
The problem is that i get one result of this function as array and the other one as object. It is a little pain in the ass, because i can't show object in that for in JS. Is there anyway to get both results in the same type? Why is this happening?
carobjects under they keycarsQuery. What kind of result were you expecting? You need the cars to be objects because you have key-value pairs, and you want all the cars to be an array, because it's an array of cars (otherwise you might lose the order information if it were an object, though that probably doesn't happen anymore)