Laravel 8 api and web routes

  laravel, laravel-routing

I am trying to have same routes for both, api and web endpoints, so that the code is easier to maintain and because both will use basically same URLs with same Controllers. Controllers are already written to return a proper response, so if request comes from API, it will return JSON and if from browser, it will return html response. Web responses are already tested and working properly, until I added api routes, then the api routes overwrite web routes and nothing works anymore.

I started with a simple option: authentication. As said, both web and api will use same URL endpoints, difference will be in (sub)domain, one will respond on www.example.com and other on api.example.com.

RouteServiceProvider.php:

public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::domain('api.example.com')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    });
}

routes/api.php:

$authMiddleware = ['auth:sanctum'];
require_once('auth.php');

routes/web.php:

$authMiddleware = ['auth'];
require_once('auth.php');

routes/auth.php (shortened):

Route::prefix('auth')->group(function() use ($authMiddleware) {
    Route::get('login', [AuthenticatedSessionController::class, 'create'])
        ->middleware(['guest'])
        ->name('login');

    $limiter = config('fortify.limiters.login');

    Route::post('login', [AuthenticatedSessionController::class, 'store'])
        ->middleware(array_filter([
            'guest',
            $limiter ? 'throttle:'.$limiter : null,
        ]))
        ->name('login.store');

    Route::middleware($authMiddleware)->group(function() {
        Route::prefix('profile')->group(function() {
            Route::get('', [ProfileController::class, 'edit'])
                ->name('user-profile-information.create')
                ->breadcrumbs(fn (Trail $trail) => $trail->parent('saas.dashboard')->push(__('Account')));

            Route::post('', [ProfileController::class, 'store'])
                ->name('user-profile-information.update');
        });
    });
});

Is it possible to have both routes with same name and same URLs? I searched google and tried few options, none worked.

Source: Laravel

Leave a Reply