Stable sort macro for Laravel Collection
Also supports sort by multiple fields
This package DOES NOT support install as a Composer Dependency.
You have to install this package manually.
- Copy
CollectionStableSortServiceProvider.php
file to your Laravel Application'sapp/Providers
directory. - Register service provider by adding a line below in
config/app.php
file'sproviders
array.App\Providers\CollectionStableSortServiceProvider::class
or check this to how to register a service provider.
- PHP >= 7.0
- Laravel >= 5.5
$collection->stableSort();
$collection->stableSort('field_name');
or
$collection->stableSort(['field_name']);
or
$collection->stableSort(['field_name' => 'asc']);
$collection->stableSort(['field_name' => 'desc']);
$collection->stableSort(function ($a, $b) { ... });
$collection->stableSort([
'first',
'second' => 'desc',
function ($a, $b) { ... },
]);
Explanation
- sort by 'first' field in ascending order first
- if 'first' field is equal, then sort by 'second' field in descending order
- if 'second' field is also same, then sort by the callback function (same as PHP's
usort()
function)
Copyright 2020 Jongmin Choe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.