Zakalwe
Zakalwe

Reputation: 1613

Using "namespace" method in RouteServiceProvder in Laravel package

I am creating a laravel package and have this setup at /packages/mycompany/mypackage.

I want to use a RouteServiceProvider to register some routes and specifically pass in a namespace so I don't have to fully qualify my controllers when using this file.

I understand that to load my routes from a package I should use loadRoutesFrom in the boot method of my main ServiceProvider:

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

This works fine and I can use the routes defined there however I have to fully namespace my controllers. Ideally, I want to be able to call these simply with no namespacing (and not by wrapping them in namespace) - much like how the routes work for a Laravel app (I'm using a package).

I saw that the 'namespace' method in \App\Providers\RouteServiceProvider can define a namespace to be used in a given routes file so have been using my own RouteServiceProvider with the following method:

public function map()
{
    Route::domain('api'.env('APP_URL'))
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(__DIR__.'/../../routes/api.php');
}

(As an aside - if I use the map method here - is the loadRoutesFrom call above necessary?)

My route service provider is registered via the main Service Provider:

public function register()
{
    $this->app->register(\MyCompany\MyPackage\Providers\RouteServiceProvider::class);
}

However when I access my app, I get a complaint that my controller doesn't exist - which can be fixed by properly namespacing my controllers in routes/api.php which is what I want to avoid.

Route::get('/somepath', 'MyController@show'); 

How do I leverage namespace so I don't have to fully qualify my controllers?

Upvotes: 2

Views: 1291

Answers (1)

lagbox
lagbox

Reputation: 50491

loadRoutesFrom is a helper that checks to see if the routes are cached or not before registering the routes.

You can start defining a group of routes then call loadRoutesFrom in that group in your provider's boot method:

Route::group([
    'domain' => 'api'. config('app.url'), // don't call `env` outside of configs
    'namespace' => $this->namespace,
    'middleware' => 'api',
], function () {
    $this->loadRoutesFrom(__DIR__.'/../../routes/api.php');
});

Or if you prefer the method style of setting the attributes:

Route::domain('api'. config('app.url'))
    ->namespace($this->namespace)
    ->middleware('api')
    ->group(function () {
        $this->loadRoutesFrom(__DIR__.'/../../routes/api.php');
    });

This is how Laravel Cashier is doing it:

https://github.com/laravel/cashier/blob/10.0/src/CashierServiceProvider.php#L86

Upvotes: 2

Related Questions