首页 > 解决方案 > Laravel 路由访问类别和显示方法

问题描述

要显示我使用以下路线的博客列表

// Blog List
Route::name('blog')->get('blog', 'Front\BlogController@index');

例如:http ://www.mypropstore.com/blog/

要显示博客类别,

Route::name('category')->get('blog/{category}', 'Front\PostController@category');

例如:http ://www.mypropstore.com/blog/buy-sell

为了显示博客详细信息、评论和标签详细信息,我们使用了“帖子”中间件

// Posts and comments
Route::prefix('posts')->namespace('Front')->group(function () {
    Route::name('posts.display')->get('{slug}', 'PostController@show');
    Route::name('posts.tag')->get('tag/{tag}', 'PostController@tag');
    Route::name('posts.search')->get('', 'PostController@search');
    Route::name('posts.comments.store')->post('{post}/comments', 'CommentController@store');
    Route::name('posts.comments.comments.store')->post('{post}/comments/{comment}/comments', 'CommentController@store');
    Route::name('posts.comments')->get('{post}/comments/{page}', 'CommentController@comments');
});

例如:http ://www.mypropstore.com/posts/apartment-vs-villa-which-is-the-right-choice-for-you

现在我想将博客详细信息 url 页面更改为

http://www.mypropstore.com/blog/apartment-vs-villa-which-is-the-right-choice-for-you- {{blogid}}

例如:http ://www.mypropstore.com/blog/apartment-vs-villa-which-is-the-right-choice-for-you-54

如果我更改上述格式,则会与类别页面冲突。任何人都知道如何设置博客详细信息页面的路由(中间件“帖子”)

标签: laravel

解决方案


假设blogid部分,在您建议的路线结束时......

http://www.mypropstore.com/blog/apartment-vs-villa-which-is-the-right-choice-for-you-{{blogid}}

...是数字,你可以这样做:

对于您的帖子详细信息页面的路由定义,请使用以下内容:

Route::name('posts.display')
    ->get('blog/{slug}-{id}', 'PostController@show')
    ->where('id', '[0-9]+');

这样做是为了确保该路由仅与遵循该模式的路径匹配,blog/{slug}-{id}但限制id您的路由部分必须是数字,即仅包含一个或多个数字。

您需要确保该路线出现与您的路线匹配的category路线之前,否则该category路线将优先。

你的控制器应该有这样的 show 方法:

class PostController extends Controller
{
    public function show($slug, $id)
    {
        // $id will contain the number at the end of the route
        // $slug will contain the slug before the number (without the hyphen)

        // You should be able to do this to get your post.
        $post = Post::findOrFail($id);
        dd($post);
    }
}

推荐阅读