Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devondahon's avatar

api route prefix lost with $this->loadRoutesFrom(__DIR__ . '/../routes/api.php');

I'm registering API routes in a package service provider like this:

$this->loadRoutesFrom(__DIR__ . '/../routes/api.php');

But then, the api/ route prefix is not applied anymore to routes set in api.php, should I put the routes in:

Route::prefix('api')->group(function () {
...
}

Or do I have something misconfigured ?

0 likes
5 replies
devondahon's avatar

@martinbean

Ok, indeed, the prefix is added in the route provider:

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

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

How to adapt the same configuration to MyPackageServiceProvider.php below?

class MyPackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->loadRoutesFrom(__DIR__ . '/../routes/api.php');
    }
}

martinbean's avatar

@devondahon Your package isn’t loaded in the RouteServiceProvider, so you’ll need to apply any prefixes, middleware, etc to any loads you load in your packages’ service providers.

devondahon's avatar

@martinbean Thanks Martin! So for instance, how to add ->prefix('api') to my routes in MyPackageServiceProvider.php ?

Something like this ?

$this->loadRoutesFrom(__DIR__ . '/../routes/api.php')->prefix('api');
martinbean's avatar
Level 80

@devondahon You can just use the Route facade as you can in a Laravel application proper:

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class YourPackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Route::middleware('api')->prefix('api')->group(function () {
            $this->loadRoutesFrom(__DIR__ . '/../routes/api.php');
        });
    }
}
3 likes

Please or to participate in this conversation.