Laravel 4 - 用户友好的URL

时间:2014-12-03 02:52:07

标签: url laravel laravel-4 routes

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

我指定了一条路线:

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

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

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

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

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

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

我正在尝试检索具有层次结构的类别,因此网址将根据以下内容而有所不同:

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

/store/categories/{urlname} 

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

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

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

1 个答案:

答案 0 :(得分: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');
}
相关问题