Vidol Chalamov
Vidol Chalamov

Reputation: 73

Sort Laravel collection with relationship count

I am trying hard for few days but I just cannot get it to work.

Here is example, I have Laravel model Test, and Questions, Question model have test_id property inside it. I want to sort Test collection by number of questions that exists with test_id = id of the given test.

I have tried both

$tests = Test::select(
        array(
            '*',
            DB::raw('(SELECT count(*) FROM questions WHERE test_id = id) as count_questions'))
    )->with('questions')->orderBy('count_questions','desc')->paginate(5);

and

$tests = Test::has('questions', '>', 3 )->with('questions')->get()->sortBy(function($test)
    {
        return $test->questions->count();
    });

but result is the same, collection is not sorted.

I use json response if that matters and when I try to echo $test->questions->count(); I get number of questions for every test.

Upvotes: 1

Views: 515

Answers (1)

Vidol Chalamov
Vidol Chalamov

Reputation: 73

It turns out that sorting don't work when I return like this:

return response()->json($tests);

but it works perfectly fine when I return like this:

return response()->json($tests->values()->all());

For me this is very strange behaviour, i have never faced something like this before, if someone can explain it I will be thankful.

Upvotes: 1

Related Questions