<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
creativecrafts / laravel-sort-collection example snippets
return [
/**
* The default sort direction to use when sorting a collection.
* supported: asc, desc
*/
'sort_direction' => 'desc',
];
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()
use CreativeCrafts\SortCollection\Sort;
// In your controller or service
$users = Sort::encryptedColumn(User::query(), 'encrypted_email', 'asc');
use CreativeCrafts\SortCollection\Sort;
// Get all users first
$users = User::all();
// Sort by multiple columns (last sort has the highest priority)
$sortedUsers = Sort::multipleColumns($users, [
'name' => 'asc',
'encrypted_email' => 'desc',
'created_at' => 'desc'
]);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.