Reputation: 9904
I want to access a controller name-space using the parameter in a route URL. Is something like this possible?
Route::group(['namespace' => 'My\Name\Space\{clientId}\Controllers', 'middleware' => 'api'], function () {
Route::get('api/v1/clients/{clientId}/test', 'TestController@test');
});
So
api/v1/clients/example/test
Would load the TestController
class with namespace My\Name\Space\example\Controllers
running method test
Since I am using laravel (and writing a package - so using a ServiceProvider) I would think there is somewhere I could hook in / override (and manipulate) the url parameter before the logic for deciding the controllers and controller methods are assigned.
I wish to do this with quite a few routes.
Upvotes: 0
Views: 1649
Reputation: 14620
Firstly for this it's best to start with the RouteServiceProvider
located in the App\Providers
namespace. You'll notice that the routes.php
is included within a route group that defines a namespace to App\Http\Controllers
. If you want to use a different namespace then it may be best to override this and either declare routes in the service provider or modify the wrapping group and use routes.php
.
To get your desired result, you will need to get the clientId
from the request object before your build the controllers. For the sake of commands that do not have a request object (artisan route:list
) it's always best to default this as well. Note this is untested, if the Request::route
is always returning null and defaulting, you can use segment()
instead to get a specific url fragment.
**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
// Attempt to get the route parameter clientId
// or assign as Default
$param = Request::route('clientId') ? : 'Default';
$namespace = 'App\\' . $param;
$router->group([
'namespace' => $namespace,
'prefix' => 'api/v1/'
], function ($router) {
// Ideally create a seperate apiroutes.php or something similar
require app_path('Http/routes.php');
});
}
Now within your routes.php
you wouldn't need a group, Just the bindings as you have them.
// The controller at namespace App\{clientId}\ will be used
Route::get('clients/{clientId}/test', 'AController@getTest');
Upvotes: 1