creativecrafts/laravel-sort-collection

A simple package to sort query collections.

1.2.0 2024-03-18 08:19 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

A simple handy package to sort query collections.

Installation

You can install the package via composer:

composer require creativecrafts/laravel-sort-collection

You can publish the config file with:

php artisan vendor:publish --tag="sort-collection-config"

This is the contents of the published config file:

return [
  /**
     * The default sort direction to use when sorting a collection.
     * supported: asc, desc
     */
    'sort_direction' => 'desc',
];

Optionally, you can publish the views using

Usage

use CreativeCrafts\SortCollection\Sort;
// simple collection example
$collection = collect([
     ['name' => 'John', 'age' => 30],
     ['name' => 'Jane', 'age' => 25],
     ['name' => 'Jack', 'age' => 40],
]);
$sortKey = 'age'; // string
$sortDirection = 'desc'; // string
$sortedCollection = Sort::collection($collection, $sortKey, $sortDirection);
// Sort direction is optional, it will use the default sort direction from the config file if not provided(by default it is desc)

// output:
[
          ['name' => 'John', 'age' => 40],
          ['name' => 'Jane', 'age' => 30],
          ['name' => 'Jack', 'age' => 25],
 ]


// eloquent example
// This is useful when you have encrypted fields in your model. Querying the model will decrypt the fields,
// then you can sort the collection using Sort::collection() method.
// Sort direction is optional, it will use the default sort direction from the config file if not provided(by default it is desc)


$query = User::query()
            ->select('name', 'age')
            ->get();

$sortKey = 'age'; // string
$sortDirection = 'asc'; // string
$sortedCollection = Sort::collection($collection, $sortKey, $sortDirection);

//output:
[
          ['name' => 'Jack', 'age' => 25],
          ['name' => 'Jane', 'age' => 30],
          ['name' => 'John', 'age' => 40],
 ]
You can also retrieve the default sort direction from the config file.
use CreativeCrafts\SortCollection\Sort;

Sort::getDefaultSortDirection()

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.