Skip to content

Instantly share code, notes, and snippets.

@iksaku
Created September 19, 2020 18:31
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iksaku/8be40fea8b6feb85e2f1a8acf29a8fbe to your computer and use it in GitHub Desktop.
Save iksaku/8be40fea8b6feb85e2f1a8acf29a8fbe to your computer and use it in GitHub Desktop.
A helper trait that provides basic PHP compatibility with @livewire's Sortable package
<?php
trait Sortable
{
/**
* This function receives a $newOrder array parameter, which contains the order in which
* we should sort our items after being dragged in the UI. The format of the $newOrder is:
*
* [
* newIndex => [
* order => Numerical order, used in case index keys don't preserve order
* value => Reference to the items being dragged. In our case, the "previous index" that the item had.
* ]
* ]
*
* With this in mind, we simplify the process by using collection methods and
* keep the code cleaner and a little more descriptive by itself.
*
* @see https://github.com/livewire/sortable
*
* @param array $haystack
* @param array $orderEvent
*/
protected function onSort(array &$haystack, array $orderEvent): void
{
$haystack = collect($orderEvent)
->sortBy('order')
->map(fn(array $ref) => $haystack[(int) $ref['value']])
->toArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment