Laravel Forwarding Route To Another Route File

1.1k views Asked by At

I'm building enterprise modular Laravel web application but I'm having a small problem.

I would like to have it so that if someone goes to the /api/*/ route (/api/ is a route group) that it will go to an InputController. the first variable next to /api/ will be the module name that the api is requesting info from. So lets say for example: /api/phonefinder/find

In this case, when someone hit's this route, it will go to InputController, verifiy if the module 'phonefinder' exists, then sends anything after the /api/phonefinder to the correct routes file in that module's folder (In this case the '/find' Route..)

So:

/api/phonefinder/find - Go to input controller and verify if phonefinder module exists (Always go to InputController even if its another module instead of phonefinder)

/find - Then call the /find route inside folder Modules/phonefinder/routes.php

Any idea's on how to achieve this?

2

There are 2 answers

0
Yavuz Koca On BEST ANSWER

Middlewares are designed for this purpose. You can create a middleware by typing

php artisan make:middleware MiddlewareName

It will create a middleware named 'MiddlewareName' under namespace App\Http\Middleware; path.

In this middleware, write your controls in the handle function. It should return $next($request); Dont change this part.

In your Http\Kernel.php file, go to $routeMiddleware variable and add this line:

'middleware_name' => \App\Http\Middleware\MiddlewareName::class,

And finally, go to your web.php file and set the middleware. An example can be given as:

Route::middleware(['middleware_name'])->group(function () {
    Route::prefix('api')->group(function () {
        Route::get('/phonefinder', 'SomeController@someMethod');
    });
});

Whenever you call api/phonefinder endpoint, it will go to the Middleware first.

0
d3jn On

What you are looking for is HMVC, where you can send internal route requests, but Laravel doesn't support it.

If you want to have one access point for your modular application then you should declare it like this (for example):

Route::any('api/{module}/{action}', 'InputController@moduleAction');

Then in your moduleAction($module, $action) you can process it accordingly, initialize needed module and call it's action with all attached data. Implement your own Module class the way you need and work from there.

Laravel doesn't support HMVC, you can't have one general route using other internal routes. And if those routes (/find in your case) are not internal and can be publicly accessed then also having one general route makes no sense.