【问题标题】:Dynamic routes with Laravel 8Laravel 8 的动态路由
【发布时间】:2021-03-31 01:46:48
【问题描述】:

我对 Laravel 中的路线有疑问。我正在开发 DMS(文档管理系统),我需要创建文件夹和无限的子文件夹。

这导致我挡住了制作成百上千条路线以实现目标的方式。

我需要制作完全动态的路线,如下例:

('/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

这导致我为每个子文件夹级别创建无限路径。

如何为动态子文件夹级别制作动态路由?

提前致谢。

【问题讨论】:

    标签: laravel routes laravel-8


    【解决方案1】:

    不这样做,您最终会遇到很多路由和性能问题。而是只做一个带有可选参数的路由作为parent 文件夹。

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

    在您的数据库中,每个文件夹都应该有一个 id 和一个 parent id
    parent id 为空时,这意味着它是一个根文件夹。 然后可以递归获取所有子/父文件夹

    【讨论】:

      【解决方案2】:

      您可以使用通配符参数:

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

      那么您的控制器路由将是:

      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();
           } 
      }
      

      【讨论】:

      • 感谢您的回复和帮助,非常感谢。
      猜你喜欢
      • 2021-08-17
      • 2021-09-01
      • 2017-07-19
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多