Global route in Laravel 5

- 1 answer

Ad

Some context: I've setup my Laravel 5 app to be split into modules. The boot() function in my AppServiceProvider looks like this:

public function boot()
{
    // We want to register the modules in the Modules folder
    $modulesPath = app_path() . '/Modules';
    $handle      = opendir($modulesPath);

    // Loop through the module directory and register each module
    while (($module = readdir($handle)) !== false) {
        if ($module != "." && $module != ".." && is_dir("{$modulesPath}/{$module}")) {
            // Check if there are routes for that module, if so include
            if (file_exists($modulesPath . '/' . $module . '/routes.php')) {
                include $modulesPath . '/' . $module . '/routes.php';
            }

            // Check if there are views for that module, if so set a namespace for those views
            if (is_dir($modulesPath . '/' . $module . '/Views')) {
                $this->loadViewsFrom($modulesPath . '/' . $module . '/Views', strtolower($module));
            }
        }
    }
}

The idea is to be able to keep things separated in modules, but also have global routes and a global controller. Therefore, each module has its own routes.php file that looks something like this:

<?php

Route::group(array('module'=>'MyModule','namespace' => 'NexusHub\Modules\MyModule\Controllers'), function() {
    Route::resource('mymodule', 'MyModuleController');
});

I then have a global routes.php file that looks like this:

<?php

Route::any('{catchall}', '[email protected]')->where('catchall', '(.*)');

Route::group(array('module'=>'Global'), function() {
    Route::resource('', 'GlobalController');
});

The problem I'm running into is that it seems my catchall route isn't picking up for the modules. The modules run their own routes but the catchall route is ignored.

As far as why I'm trying to accomplish this, for now the purpose is that all modules use the same layout, and that layout requires some data to be retrieved always, so the global controller would grab what's needed and make it available to the layout. But I suppose there may be some other things in the future where having a global route file that can catch multiple different routes based on arbitrary rules and run additional code would come in handy.

UPDATE: Removed the line that included the global routes since I realized they already got included by default anyway.

Ad

Answer

Ad

I ended up doing what I wanted using middleware instead (see https://laravel.com/docs/master/middleware#global-middleware).

In my case I used something similar to the BeforeMiddleware class example and registered it in the $middleware property of my app/Http/Kernel.php class since it's global and not route dependant.

Ad
source: stackoverflow.com
Ad