【问题标题】:Laravel 4 - User-friendly URLsLaravel 4 - 用户友好的 URL
【发布时间】:2015-01-31 11:48:02
【问题描述】:

我正在使用 etrepat/baum composer 包在我的 Laravel 4 应用程序中创建类别和子类别。问题在于,根据请求的类别是根目录还是子目录,url 应该不同。

我已经指定了一条路线:

Route::get('/store/categories/{urlname}', array(
    'as'  =>  'category',
    'uses'  =>  'StoreController@getCategories'
));

就像现在一样,类别和子类别都将使用此路由来获取特定类别并通过 url,例如:

/store/categories/{urlname} -where the urlname might be a category or a subcategory.

我的控制器功能中有以下查询:

$category = Category::whereUrl_name($urlname)->with('seo')->first();

在数据库中,类别表 - 如果创建了子类别,它还将其父类别的名称存储在 parent_name 字段中。

我正在尝试检索具有层次结构的类别,因此 url 将根据:

- 如果请求的类别是根节点:

/store/categories/{urlname} 

- 如果请求的类别是子类别,则:

/store/categories/{parent_name}/{urlname}

关于如何解决此类问题的任何想法?

【问题讨论】:

    标签: url laravel laravel-4 routes


    【解决方案1】:

    你的路线

    Route::get('/store/categories/{urlname}', array(
        'as'  =>  'category',
        'uses'  =>  'StoreController@getCategories'
    ))->where('urlname', '(.*)?');
    

    StoreController 中的函数

    public function getCategories($urlname) {    
    
        $categories = explode('/', $urlname);
    
        $main = Category::whereUrl_name(end($categories))->with('seo')->first();
        reset($categories);
    
        if ($main)
        {
            $ancestors = $main->getAncestors();
    
            $valid = true;
    
            foreach ($ancestors as $i => $category)
            {
                if ($category->url_name !== $categories[$i])
                {
                    $valid = false;
                    break;
                }
            }
    
            if ($valid)
            {
                /* continue on with your code here ... */
            }
        }
    
        App::abort('404');
    }
    

    【讨论】:

    • 这不是我想要的。由于您的解决方案使用第二条路由到另一个函数来获取子类别(getSubcategories)。这也会有一个类似的网址:/store/subcategories/{parent_name}/{urlname}。
    • 我认为这两条路线是您自定义的目标。你应该明确你的目标。所以你只想要第一条路线? {urlname} 可以是一个类别或子类别,但我们不知道哪个是正确的?那么你的问题是什么?如果是类别,您希望您的函数得到哪个答案?如果是子类别,您希望得到哪个答案?也许您可以在您的问题中提供示例数据?
    • 我想要实现的是制作网址:example.com/store/categories/[category_urlname] (Parent) example.com/store/categories/[parent_name]/[category_urlname] (孩子,有父母)。现在的问题是,如果是父母或孩子,它将使用:example.com/store/categories/[category_urlname]
    • 对不起,我还是没听懂。如果你想打电话给example.com/category/[parent]/[child],那么你需要一条路线。或者你想创建链接?我不明白你的目标是什么。
    • 我在这里发现了一个非常相似的问题:laravel.io/forum/…
    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2012-07-05
    • 2010-11-07
    • 2013-09-03
    • 2011-01-07
    相关资源
    最近更新 更多