DEV Community

Lloric Mayuga Garcia
Lloric Mayuga Garcia

Posted on

Adding functionality to add entire folder to a route in Laravel

    // App\Providers\RouteServiceProvider

    public function map()
    {
        Route::macro('requireFolder', function (string $folder) {
            try {

                $it = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($folder)
                );

                while ($it->valid()) {
                    if (
                        !$it->isDot() &&
                        $it->isFile() &&
                        $it->isReadable() &&
                        $it->current()->getExtension() === 'php'
                    ) {
                        require $it->key();
                    }

                    $it->next();
                }
            } catch (Exception $e) {
                dd(__METHOD__, $e->getMessage());
            }
        });

        $this->mapWebApiRoutes();
        $this->mapWebRoutes();
    }
Enter fullscreen mode Exit fullscreen mode

now you can just use this

Route::group([
    'prefix' => 'admin',
], function()
{
    Route::requireFolder(__DIR__.'/backend');
});

Enter fullscreen mode Exit fullscreen mode

all php files will automagically require

Top comments (0)