Skip to content

Instantly share code, notes, and snippets.

@luiseduardobraschi
Created March 26, 2024 21:59
Show Gist options
  • Save luiseduardobraschi/02a4766e7637a60f315e209110b933fc to your computer and use it in GitHub Desktop.
Save luiseduardobraschi/02a4766e7637a60f315e209110b933fc to your computer and use it in GitHub Desktop.
Dynamic routing in Laravel

The URL matched format for a URL like "user/manage/id/1/role/admin" is:

controler: user
action: manage
params: [ 'id' => 1, 'role' => 'admin' ]

<?php
Route::match(
['get', 'post'],
'{controller}/{action?}/{params?}',
function ($controller, $action = 'index', $params = '') {
$params = explode('/', $params);
$methodParams = [];
foreach ($params as $key => $param) {
if ($key % 2)
$methodParams[$params[$key - 1]] = $param;
}
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $methodParams);
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment