首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel嵌套路由

Laravel嵌套路由
EN

Stack Overflow用户
提问于 2020-05-18 17:48:43
回答 1查看 405关注 0票数 0

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

目录表:

代码语言:javascript
复制
category1
--category11
--category12
----category121
----category122
--category13

文章表:

代码语言:javascript
复制
news
--news1
--news2

Вasic Laravel路由如下所示:

代码语言:javascript
复制
Route::get('category/{id}', 'categoryController@show');
Route::get('news/{id}', 'newsController@show');

但是在这种情况下,对于每个目录的URL,“类别”URL的片段是必需的,而对于每个新的URL,“新闻”URL的片段是必需的

如何使用Laravel路由来路由以下urls:

代码语言:javascript
复制
http://sitename.com/category1
http://sitename.com/category1/category11
http://sitename.com/category1/category12/category121
http://sitename.com/news
http://sitename.com/news/news1
EN

回答 1

Stack Overflow用户

发布于 2020-05-18 18:04:14

您将需要一个“全部捕获”路由(如果您希望所有路径都是可配置的,则在所有其他路由之后注册)。

然后你可以在斜杠上分解路径,检查每个元素都是一个有效的类别段塞,并且也是前一个类别的子元素。

代码语言:javascript
复制
// All other routes...

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

您也可以使用自定义路由绑定来完成此操作:

代码语言:javascript
复制
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;
});

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

代码语言:javascript
复制
class CategoryController extends Controller
{
    public function show(Category $category)
    {
        // Given a URI like /clothing/shoes,
        // $category would be the one with slug = shoes
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61866831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档