Ad

Dynamically Map Routes In Laravel

Are there any solutions to make Laravel routes dynamically call the controller and action? I couldn't find anything in the documentation.

<?php

Route::get('/{controller}/{action}',
    function ($controller, $action) {
    })
    ->where('controller', '.*')
    ->where('action', '.*');
Ad

Answer

Laravel does not have an out of the box implementation that automatically maps routes to controller/actions. But if you really want this, it is not that hard to make a simple implementation.

For example:

Route::get('/{controller}/{action}', function ($controller,$action) {
    return resolve("\\App\\Http\Controllers\\{$controller}Controller")->$action();
})->where('controller', '.*')->where('action', '.*');

Keep in mind, this example will not automatically inject objects in your action and url parameters are also not injected. You will have to write a bit more code to do this.

Ad
source: stackoverflow.com
Ad