【问题标题】:Laravel nested routesLaravel 嵌套路由
【发布时间】:2020-09-04 02:07:26
【问题描述】:

我使用 laravel 7 并在数据库中存储以下树结构:

目录表:

category1
--category11
--category12
----category121
----category122
--category13

文章表:

news
--news1
--news2

基本的 Laravel 路由看起来像:

Route::get('category/{id}', 'categoryController@show');
Route::get('news/{id}', 'newsController@show');

但在这种情况下,每个目录的 URL 都需要“类别”url 的段,并且 每个新的 URL 都需要“news” url 的段

如何使用 Laravel Routes 路由以下 url:

http://sitename.com/category1
http://sitename.com/category1/category11
http://sitename.com/category1/category12/category121
http://sitename.com/news
http://sitename.com/news/news1

?

【问题讨论】:

    标签: laravel routes


    【解决方案1】:

    您需要一条“包罗万象”的路线(如果您希望 所有 路径可配置,请在所有其他路线之后注册)。

    然后,您可以在斜杠上展开路径,检查每个元素是否是有效的类别 slug,并且也是前一个类别的子项。

    // All other routes...
    
    Route::get('/{category_path}', 'CategoryController@show')->where('category_path', '.*');
    

    您也可以使用自定义路由绑定来做到这一点:

    Route::bind('category_path', function ($path) {
        $slugs = explode('/', $path);
    
        // Look up all categories and key by slug for easy look-up
        $categories = Category::whereIn('slug', $slugs)->get()->keyBy('slug');
    
        $parent = null;   
    
        foreach ($slugs as $slug) {
            $category = $categories->get($slug);
    
            // Category with slug does not exist
            if (! $category) {
                throw (new ModelNotFoundException)->setModel(Category::class);
            }
    
            // Check this category is child of previous category
            if ($parent && $category->parent_id != $parent->getKey()) {
                // Throw 404 if this category is not child of previous one
                abort(404);
            }
    
            // Set $parent to this category for next iteration in loop
            $parent = $category;
        }
    
        // All categories exist and are in correct hierarchy
        // Return last category as route binding
        return $category;
    });
    

    然后您的类别控制器将接收路径中的最后一个类别:

    class CategoryController extends Controller
    {
        public function show(Category $category)
        {
            // Given a URI like /clothing/shoes,
            // $category would be the one with slug = shoes
        }
    }
    

    【讨论】:

    • 谢谢!路由到一个控制器是一个不错的决定。但是如果我想路由到不同的控制器相关数据库怎么办?我可以从 CategoryController 调用另一个控制器,但这是不好的代码做法。
    • @mickrus 我真的不知道。您询问了如何处理多级路由,这就是提供的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2016-06-20
    • 2015-11-17
    • 1970-01-01
    • 2013-07-15
    • 2015-08-01
    • 2014-12-09
    相关资源
    最近更新 更多