Replies: 1 comment
-
I was able to achieve this by extending/overwritting the provider <?php
namespace App\Providers;
use Spatie\RouteAttributes\RouteAttributesServiceProvider as ServiceProvider;
use Spatie\RouteAttributes\RouteRegistrar;
class RouteAttributesServiceProvider extends ServiceProvider
{
protected function registerRoutes(): void
{
if (! $this->shouldRegisterRoutes()) {
return;
}
$routeRegistrar = (new RouteRegistrar(app()->router))
->useMiddleware(config('route-attributes.middleware') ?? []);
collect(config('route-attributes.directories'))->each(function (string|array $directory, string|int $namespace) use ($routeRegistrar) {
if (is_array($directory)) {
// This is the main change
$routeRegistrar->useRootNamespace($directory['namespace'] ?? app()->getNamespace());
app()->router->group($directory, fn () => $routeRegistrar->registerDirectory($namespace));
} else {
is_string($namespace)
? $routeRegistrar
->useRootNamespace($namespace)
->useBasePath($directory)
->registerDirectory($directory)
: $routeRegistrar
->useRootNamespace(app()->getNamespace())
->useBasePath(app()->path())
->registerDirectory($directory);
}
});
}
private function shouldRegisterRoutes(): bool
{
if (! config('route-attributes.enabled')) {
return false;
}
if ($this->app->routesAreCached()) {
return false;
}
return true;
}
} And this config <?php
return [
/*
* Automatic registration of routes will only happen if this setting is `true`
*/
'enabled' => true,
/*
* Controllers in these directories that have routing attributes
* will automatically be registered.
*/
'directories' => [
app_path('Http/Controllers/Front') => [
'prefix' => '',
'middleware' => ['web']
],
app_path('Http/Controllers/Admin') => [
'prefix' => 'admin',
'middleware' => ['web', 'admin']
],
app_path('Http/Controllers/Api') => [
'prefix' => 'api',
'middleware' => ['api']
],
],
/**
* This middleware will be applied to all routes.
*/
'middleware' => [
]
]; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
A common project structure is to have 3 different types of routes
Eg:
They would normally be configured using the RouteServiceProvider
There doesn't seem to be a way to configure the package to have this kind of behavior except than to specify the prefix and middlewares on top of each controller in those directories
It would be much nicer if there was a way to configure this in the config file
Beta Was this translation helpful? Give feedback.
All reactions