Created
January 24, 2014 12:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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