Dynamic routes with Laravel 8

Viewed 2373

I have a problem with routes in Laravel. I am working on DMS (Document Management System), I need to make folders and infinite sub-folders.

This leeds me to block the way to make hundreds or thousands of routes to achieve the goal.

I need to make fully dynamic routes as the following example:

('/folders',[FolderController::class , 'index']) //to retrieve all folders
('/folders/{x}' , [FolderController::class , 'show']) // to retrieve level one sub-folder
('/folders/{x}/{y}' ,[FolderController::class , 'xyz'])  // to retrieve level two sub-folder

This leeds me to make infinite routes for each sub-folders level.

How to make dynamic routes for dynamic sub-folders level?

Thanks in advance.

2 Answers

You can use a wildcard parameter:

Route::get('/folders/{x}' , [FolderController::class , 'show'])
    ->where('x', '.*');

then your controller route would be:

public function show($x = '') {
     $path = explode('/', $x);
     // $path is an array with the directory structure
     // Do whatever you want with it e.g.
     if (empty($path)) {
         return $this->index();
     } 
}

Don't do this you will end up with a lot a route and performance issues. Instead do only one route with an optional parameters as the parent folder.

'/folders/{x?}' , [FolderController::class , 'show']);

In your db every folder should have an id and a parent id.
when the parent id is null this mean it's a root folder. Then you can recursively get all the child/parent folder

Related