Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel dynamic controller route

I use Laravel 5.4 and now I want to make dynamic route to controller which mean I can access UserController and Profile function throw route directly, for example.

GET http://localhost/user/profile?userid=123

The example URL above will access UserController and function profile with dynamic parameters after ?. And if I want to access different controller, I just need to change user param to Controller name.

I created a route like this and it works.

Route::get('v1/{controller_name}/{function_name}/{query?}', function ($controller_name, $function_name){

    $app = app();
    $controller = $app->make('\App\Http\Controllers\Api\\'.$controller_name.'Controller');
    return $controller->callAction($function_name, $parameters = array());
});

But I don't know how to pass parameters.

Any other better way to do this?

like image 425
Johnny Nguyen Avatar asked May 18 '17 01:05

Johnny Nguyen


Video Answer


1 Answers

I'm not sure, if I understand you correctly, but you might want to check out the following.

Route::get('v1/{controller_name}/{function_name}/{query?}',
        function ($controller_name, $function_name, $query = null) {
    var_dump($controller_name, $function_name, $query);
});

visiting http://localhost/v1/my-controller/my-function/my-parameter URL outputs:

string 'my-controller' (length=13)
string 'my-function' (length=11)
string 'my-parameter' (length=12)

visiting http://localhost/v1/my-controller/my-function URL outputs:

string 'my-controller' (length=13)
string 'my-function' (length=11)
null

And to extend the idea further, it is possible to write:

Route::get('v1/{controller_name}/{function_name}/{query?}/{query2?}',
        function ($controller_name, $function_name, $query = null, $query2 = null) {
    var_dump($controller_name, $function_name, $query, $query2);
});

http://localhost/v1/my-controller/my-function/my-parameter/my-parameter2

string 'my-controller' (length=13)
string 'my-function' (length=11)
string 'my-parameter' (length=12)
string 'my-parameter2' (length=13)

http://localhost/v1/my-controller/my-function

string 'my-controller' (length=13)
string 'my-function' (length=11)
null
null

Then you can use:

// ...
return $controller->callAction($function_name, $parameters = [
    'param1' => $query,
    'param2' => $query2,
]);
// ...
like image 65
Dmytro Dzyubak Avatar answered Nov 15 '22 01:11

Dmytro Dzyubak