Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 collection sortByDesc not working

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');
like image 430
Firdavs Khodzhiev Avatar asked Oct 20 '25 13:10

Firdavs Khodzhiev


2 Answers

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();
like image 171
Biswa Avatar answered Oct 23 '25 03:10

Biswa


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.

like image 30
Farrukh Javed Avatar answered Oct 23 '25 02:10

Farrukh Javed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!