DEV Community

TRUNG VU
TRUNG VU

Posted on

Separating frontend and backend routes in Laravel

In some projects, you want to separate frontend and backend routes, now I will show how you can do it.

Create a routes/web_admin.php file

use Illuminate\Support\Facades\Route;

Route::match(['get', 'post'], '/', 'AuthController@login')->name('login');
Route::middleware('auth:admin')->group(function () {
    // dashboard
    Route::get('dashboard', 'DashboardController@dashboard')->name('dashboard');
    // logout
    Route::get('logout', 'AuthController@logout')->name('logout');
    ...

});
Enter fullscreen mode Exit fullscreen mode

Edit routes/web.php

use Illuminate\Support\Facades\Route;

Route::get('/', 'HomeController@index')->name('home');
Enter fullscreen mode Exit fullscreen mode

In the app/Providers/RouteServiceProvider.php, we need to change something:

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    ...
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        $this->mapWebAdminRoutes();
    }

    protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace.'\Frontend')
            ->group(base_path('routes/web.php'));
    }

    protected function mapWebAdminRoutes()
    {
        Route::middleware('web')
            ->prefix('admincp')
            ->name('admin.')
            ->namespace($this->namespace.'\Backend')
            ->group(base_path('routes/web_admin.php'));
    }
}
Enter fullscreen mode Exit fullscreen mode

Happy Coding:)

Top comments (0)