...

How to Create a Sorted Dropdown of Routes in Laravel

Discover how to dynamically fetch and alphabetically sort Laravel routes, creating clean and organized dropdown menus. Enhance your application's usability with step-by-step guidance on efficient route management and formatting for seamless user experience.

Introduction

  • Brief overview of why sorting routes alphabetically is useful.
  • Mention the relevance for admin panels, CMS systems, and dynamic forms.

Step 1: Fetch Routes Dynamically

  • Explain how to use Route::getRoutes() to fetch all routes.
  • Highlight the use of filtering to only include specific route patterns like home..

Step 2: Sort Routes Alphabetically

  • Introduce collect() and sortBy() to order the routes dynamically.
  • Provide a detailed code snippet to showcase the implementation.

Step 3: Format Route Names

  • Discuss formatting transformations, such as replacing underscores and adding spaces.
  • Example: home.AcademicFacilities becomes Academic Facilities.

Step 4: Create the Dropdown

  • Combine everything to render a dynamic dropdown menu.
  • Add conditional disabling of specific routes.

Conclusion

  • Summarize the benefits of organizing and sorting routes.
  • Encourage readers to try this approach in their Laravel projects.
<div class="col-md-6">
        <div class="mb-12">
            <!-- Label for the dropdown -->
            <label class="form-label"> 
                Page Name (Route Name) 
                <span class="text-danger">*</span> 
            </label>
            
            @php
                // Collect and filter routes to only include those starting with 'home.'
                $sortedRoutes = collect(Route::getRoutes())
                    ->filter(function ($route) {
                        return str_starts_with($route->getName(), 'home.');
                    })
                    ->sortBy(function ($route) {
                        // Sort alphabetically after cleaning route name
                        return str_replace(['home.', '_'], ['', ' '], $route->getName());
                    });
            @endphp
    
            <!-- Dropdown for selecting a route -->
            <select name="selected_route" wire:model="pname" id="selected_route" class="form-control">
                <option value="">Select page (NULL)</option>
    
                @foreach ($sortedRoutes as $route)
                    @php
                        // Transform route name: remove 'home.' prefix and replace underscores with spaces
                        $routeName = str_replace(['home.', '_'], ['', ' '], $route->getName());
                        
                        // Add spaces before uppercase letters for better readability
                        $routeNameFormatted = preg_replace(
                            '/([a-z])([A-Z])/', // Match lowercase followed by uppercase
                            '$1 $2',           // Add space between them
                            ucwords($routeName) // Capitalize words
                        );
                    @endphp
                    
                    <option 
                        value="{{ $route->getName() }}"
                        @if (in_array($route->getName(), ['home.homepage', 'home.withdrawals'])) 
                            disabled 
                        @endif
                        class="form-control"
                    >
                        {{ $routeNameFormatted }}
                    </option>
                @endforeach
            </select>
    
            <!-- Error message for validation -->
            @error('pname')
                <span class="error">{{ $message }}</span>
            @enderror
        </div>
    </div>


                           


2nd Example if You Want to print in table


     @php
        $routes = collect(Route::getRoutes())
            ->filter(function ($route) {
                return str_starts_with($route->getName(), 'home.');
            })
            ->sortBy(function ($route) {
                return str_replace(['home.', '_'], ['', ' '], $route->getName());
            });
    @endphp

    @foreach ($routes as $route)
        @php
            // Transform route name
            $routeName = str_replace(['home.', '_'], ['', ' '], $route->getName());
            // Add spaces before uppercase letters
            $routeNameFormatted = preg_replace(
                '/([a-z])([A-Z])/',
                '$1 $2',
                ucwords($routeName),
            );
        @endphp
        <tr>
            <td class="fw-bold">{{ $routeNameFormatted }}</td>
            <td>
                <a class="fw-bold" href="{{ route($route->getName()) }}" target="_blank">
                    {{ $routeNameFormatted }}
                </a>
            </td>
            <td>
                @if (in_array($route->getName(), ['home.homepage', 'home.withdrawals']))
                    ====
                @else
                    == New ==
                @endif
            </td>
        </tr>
    @endforeach

William Anderson

I am a versatile Full-Stack Web Developer with a strong focus on Laravel, Livewire, Vue.js, and Tailwind CSS. With extensive experience in backend development, I specialize in building scalable, efficient, and high-performance web applications.