1

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?

1
  • Your result will be an object containing array of car objects under they key carsQuery. 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) Commented Oct 29, 2020 at 18:11

3 Answers 3

1

OK i found out what happened. In one case Query returned one result so it was returned as array. When there was more then one result then it was returned as object. Thanks for the answers everyone!

Sign up to request clarification or add additional context in comments.

Comments

0

I don't how you defined cars relation in your model so you can pick the first index object from array.

class CarController extends Controller
{
    public function getCars(Request $request)
    {
        $query = Game::where($request->game_id)->cars->where('car_class_id', $request->carClassID)->sortBy('id');
    
    $data = $query->toArray();    
    return Response([
            'carsQuery' => $data[0]
        ]);
    }
}

but the proper way is using eager load cars relation and first() method

public function getCars(Request $request)
{
    $data = Game::with(['cars' => function($query) use($request) {
        $query->where('car_class_id', $request->carClassID);
    }])->where('id',$request->game_id)->first()->toArray();    
 
return Response([
        'carsQuery' => $data
    ]);
}

Comments

0

I've seen that you're missing the ->get() call in your query.

What you have:

$query = Game::where($request->game_id)
    ->cars->where('car_class_id', $request->carClassID)
    ->sortBy('id');

How it should be:

$query = Game::where($request->game_id)
    ->cars->where('car_class_id', $request->carClassID)
    ->sortBy('id')
    ->first(); // THIS is the missing call, this will return the result of your query

If you want a single result, you should add ->first(). If your query has to return more than one row, add ->get() instead.

Be aware of the different results: if you use ->first(), it will return a model (object), but if you use ->get(), the result will be a collection. That's probably why you have this results inconsistent. If you want all of them to be arrays, you can use the ->get() method so it always returns a collection, even if there's only one result

2 Comments

I've got an error "Property [cars] does not exist on the Eloquent builder instance." when i'm trying to use get()
@NoName is the relation defined in the Game model? I'd also suggest to call ->cars() so you can access the query builder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.