You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel多级分类与文章动态Slug路由优化咨询

博客应用无限层级路由优化咨询

我开发的博客应用目前运行正常,采用两级深度路由结构:www.site.com/{parent-category}/{sub-category}/{post}。但部分分类存在更深层级的子分类,导致控制器方法变得冗长且难以维护。

当前URL结构与实现示例

URL示例:
www.site.com/cancer/symptoms/<post-name>

路由定义

Route::get('/{parent?}/{child?}/{post?}', [WebSiteController::class, 'index'])->where('child', '^[a-zA-Z0-9-_\/]+$')->name('homepage');

控制器实现代码

public function index($parent = null, $child = null, $post = null)
{
    // 如果未定义slug则显示首页
    if ($parent == null && $parent == '' && $child == null && $child == '') {
        return view('website.homepage');
    } 
    // 已定义父分类但未定义子分类,显示根分类
    else if($parent !== null && $child == null)
    {
        $category = PostCategory::where('slug', $parent)->where('post_category_id', 0)->firstOrFail(); 
        
        return view('website.category', compact('category'));
    } 
    // 已定义父分类与子分类,显示子分类
    else if ($parent !== null && $child !== null) 
    {
        $category = PostCategory::where('slug', $child)->firstOrFail();

        return view('website.category', compact('category','children_toc', 'posts'));   
    }
    else {
            abort('404');
    }
}

优化需求:支持无限层级URL结构

需要实现如下格式的无限层级URL:
www.site.com/medical/diseases/cancer/symptoms/sub-category/sub-sub-category/<post-name>

如果手动为每个层级添加路由参数和控制器参数,会导致方法极度臃肿且难以维护,示例如下:

手动扩展的路由与控制器示例

Route::get('/{parent?}/{child?}/{child2?}/{child3/{child4?}?}/{post?}', [WebSiteController::class, 'index'])->where('child', '^[a-zA-Z0-9-_\/]+$')->name('homepage');
public function index($parent = null, $child = null, $child2 = null, $child3= null, etc..., $post = null)
{
    if($child !== null && $child2 == null)
    {
        $category = ....; 
        
        // do somthing
    }
   else if($child2 !== null && $child3 == null)
   {
      // do somthing
   }
  // ...
}

这种手动方式可以无限延续,但新增层级就必须修改代码。想请教是否有动态处理的方案?或者是否更适合在数据库中存储完整Slug路径(如/medical/diseases/cancer/symptoms)?

当前数据库迁移代码

public function up()
{
    Schema::create('post_category', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('post_category_id')->nullable(); 
        $table->string("name")->nullable(false);
        $table->string("slug") ;
            
        $table->timestamps();
    });
}

内容的提问来源于stack exchange,提问作者Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:50:44