The source code can be found in Illuminate/Support/Collection.php:
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
$results = [];
if ( ! $this->useAsCallable($callback))
{
$callback = $this->valueRetriever($callback);
}
// First we will loop through the items and get the comparator from a callback
// function which we were given. Then, we will sort the returned values and
// and grab the corresponding values for the sorted keys from this array.
foreach ($this->items as $key => $value)
{
$results[$key] = $callback($value, $key);
}
$descending ? arsort($results, $options)
: asort($results, $options);
// Once we have sorted all of the keys in the array, we will loop through them
// and grab the corresponding model so we can set the underlying items list
// to the sorted version. Then we'll just return the collection instance.
foreach (array_keys($results) as $key)
{
$results[$key] = $this->items[$key];
}
$this->items = $results;
return $this;
}
Since the sort() family isn't stable, this function won't be stable either.
There are stable PHP sort functions, but if you want to use them you'll need to patch Laravel.