multiple route file instead of one main route file in laravel 5

You can create as many route files as you need anywhere and then just require them in the main route file smth like:

Route::get('/', function () {
    return 'Hello World';
});

Route::post('foo/bar', function () {
    return 'Hello World';
});

require_once "../../myModule1/routes.php";
require_once "../../myModule2/routes.php"
require_once "some_other_folder/routes.php"

where you will define routes in the same way as in main


The group() method on Laravel's Route, can accept filename, so we can something like this:

// web.php

Route::prefix('admin')
    ->group(base_path('routes/admin.php'));

// admin.php
Route::get('/', 'AdminController@index');

  1. create 2 route files routes.web.php and routes.api.php.

  2. edit the RouteServiceProvider.php file to look like the example below:


<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;

class RouteServiceProvider extends ServiceProvider
{

    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $webNamespace = 'App\Http\Controllers\Web';

    protected $apiNamespace = 'App\Http\Controllers\Api';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function boot(Router $router)
    {
        //

        parent::boot($router);
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function map(Router $router)
    {

        /*
        |--------------------------------------------------------------------------
        | Web Router 
        |--------------------------------------------------------------------------
        */

        $router->group(['namespace' => $this->webNamespace], function ($router) {
            require app_path('Http/routes.web.php');
        });

        /*
        |--------------------------------------------------------------------------
        | Api Router 
        |--------------------------------------------------------------------------
        */

        $router->group(['namespace' => $this->apiNamespace], function ($router) {
            require app_path('Http/routes.api.php');
        });

    }
}

Note: you can add as many route files as you want...


You can use Request::is() so your main routes.php file will look like this:

if(Request::is('frontend/*))
{
    require __DIR__.'/frontend_routes.php;
}

if(Request::is('admin/*))
{
    require __DIR__.'/admin_routes.php;
}

You can read more here.

Tags:

Php

Laravel