I have two queries with Eloquent which I collect and merge and after i do sortByDesc
but it's not sorting collection.
$f_games = collect(Game::with('fUser', 'sUser')->where('first_user_id', Auth::user()->id)>get());
$s_games = collect(Game::with('fUser', 'sUser')->where('second_user_id', Auth::user()->id)->get());
$response = $f_games->merge($s_games)->sortByDesc('id');
You can use values()
at the end of sorting, as discussed in documentation
$gameCollection = collect($game);
$sorted = $gameCollection->sortByDesc('date');
return $sorted->values()->all();
In you case it should be
$response = $f_games->merge($s_games)->sortByDesc('id')->values();
The sortByDesc
method sorts the collection by field that belongs to some eloquent relation in your model.
If you are trying to sort collection with sortByDesc
for model itself ( your current object of model), please user orderBy
rather than sortByDesc
Example:
For model itself
{$collection_list = $this->model_name->orderBy('field_name','DESC')->get();}
For relations that will be lazy loaded in views
{$collection_list = $this->model_name->get()->sortBy('table_name.field_name', SORT_REGULAR, true);}
Note: sortByDesc
internally called sortBy()
with descending order,
true means Descending Order and false means Ascending Order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With