Laravel Tutorials

Custom Key Sorting in Laravel Collections

Published
Custom Key Sorting in Laravel Collections image

Laravel's sortKeysUsing method provides fine-grained control over how collection keys are arranged, enabling you to implement custom sort logic beyond standard alphabetical ordering.

This feature proves especially valuable when working with configuration arrays, form fields with specific display orders, or any associative data where key sequence matters for processing or display.

$collection->sortKeysUsing('strnatcasecmp');

// or

$collection->sortKeysUsing(function ($a, $b) {
    return $a <=> $b;
});

Here's an example of implementing prioritized menu ordering:

<?php

namespace App\Services;

use Illuminate\Support\Collection;

class NavigationManager
{
    public function getOrderedNavigation(array $menuItems): Collection
    {
        return collect($menuItems)
            ->sortKeysUsing(function ($a, $b) {
                // Extract position prefixes (pos1_, pos2_, etc.)
                $positionA = $this->extractPosition($a);
                $positionB = $this->extractPosition($b);
                
                // If both have position prefixes, sort numerically
                if ($positionA !== null && $positionB !== null) {
                    return $positionA <=> $positionB;
                }
                
                // Position prefixes come before unprefixed keys
                if ($positionA !== null) return -1;
                if ($positionB !== null) return 1;
                
                // Group items by section
                $sectionA = explode('_', $a)[0];
                $sectionB = explode('_', $b)[0];
                
                if ($sectionA !== $sectionB) {
                    // Custom section order
                    $sections = ['dashboard', 'users', 'content', 'settings'];
                    $indexA = array_search($sectionA, $sections);
                    $indexB = array_search($sectionB, $sections);
                    
                    if ($indexA !== false && $indexB !== false) {
                        return $indexA <=> $indexB;
                    }
                }
                
                // Default to natural case-insensitive sort
                return strnatcasecmp($a, $b);
            });
    }
    
    private function extractPosition(string $key): ?int
    {
        if (preg_match('/^pos(\d+)_/', $key, $matches)) {
            return (int) $matches[1];
        }
        
        return null;
    }
}

The sortKeysUsing method transforms how you arrange collection data, enabling semantic ordering based on your application's specific requirements.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article
Real-Time Inertia Props With Laravel Reverb image

Real-Time Inertia Props With Laravel Reverb

Read article
PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support image

PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support

Read article