Skip to content

Instantly share code, notes, and snippets.

@danharper
Created January 24, 2014 12:34
Show Gist options
  • Save danharper/8596456 to your computer and use it in GitHub Desktop.
Save danharper/8596456 to your computer and use it in GitHub Desktop.
Laravel/Eloquent Collection method to sort by a comma-separated string of IDs. Any models which do not appear in the given order are added to the end in ID order.
<?php
use Illuminate\Database\Eloquent\Collection;
class BaseCollection extends Collection {
public function sortByOrder($order, $delimeter = ',')
{
$order = is_array($order) ? $order : explode($delimeter, $order);
return $this->sortBy(function($item) use ($order) {
$found = array_search($item->id, $order);
return $found === false ? 99999 + $item->id : $found;
});
}
}
<?php
// I recommend you set the usage on a base model, and extend the base model,
// that way all your models benefit
class BaseEloquent extends Eloquent {
public function newCollection(array $models = array())
{
return new BaseCollection($models);
}
}
$property = Property::with('rooms')->get();
$property->roomOrder;
// "9,7,4,5,6,8,2"
$property->rooms->sortByOrder($property->roomOrder);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment