在 URL 中显示类别别名而不是 ID

Display Category Slug in URL Instead of ID

我是 Laravel 的新手,我发现自己一直在尝试显示类别别名而不是 ID。

eg: www.website/.../category-slug

我的网站当前显示 www.website/.../category-id。我有一个类别 table 和一个带有列的帖子 table。

posts table = | id | title | body | img | post_category_id|

post_categories table = | id | name | catslug |

控制器

public function getPostCategory($id)
{
    $postCategories = PostCategory::with('posts')
        ->orderBy('name', 'asc')
        ->get();

    $posts = Post::orderBy('id', 'desc')
        ->where('post_category_id', $id)
        ->paginate(5);

    return view('articles.category.categoriesposts')->withPosts($posts)->with('postCategories', $postCategories);
}

路线

Route::get('articles/category/{id}', [ 
    'uses'  =>  'ArticlesController@getPostCategory',
    'as'    =>  'pcategory'
]);

我尝试了很多方法,但似乎没有任何效果。任何帮助将不胜感激。

非常感谢,

灰烬

ArticlesController.php

public function getPostCategory($slug) {
    $postCategories = PostCategory::with('posts')
                    ->orderBy('name', 'asc')
                    ->where('catslug', '=', $slug)
                    ->first();

    // $postCategories->posts - already is a collection of your posts related only to the category you're looking for

        // return view
        return view ('articles.category.categoriesposts')->with('postCategories', $postCategories);


}

Route::get('articles/category/{slug}',  [ 
     'uses'  =>  'ArticlesController@getPostCategory' ,
     'as'    =>  'pcategory'
] );

就是这样。此外,您可以缩小路线代码:

Route::get('articles/category/{slug}', 'ArticlesController@getPostCategory')->name('pcategory');

这应该适合你:

**ROUTE:**

Route::get('articles/category/{slug}',  [ 
'uses'  =>  'ArticlesController@getPostCategory' ,
'as'    =>  'pcategory'
] );

**CONTROLLER**

public function getPostCategory($slug) {
    $postCategories = PostCategory::with('posts')
                    ->orderBy('name', 'asc')
                    ->get();

    $posts = Post::orderBy('id', 'desc')
        ->whereHas('post_category', function ($query) use ($slug) {
            $query->where('catslug', 'like', $slug);
        })->paginate(5);

        // return view
        return view ('articles.category.categoriesposts')->withPosts($posts)->with('postCategories', $postCategories);


}

你可以试试这个:

<?php 
    if(isset($_GET['slug'])){
        $get_slug = $_GET['slug'];
        $query = "SELECT * FROM `table_name` WHERE get_slug ='$get_slug'";
        if($result = mysqli_query($conn, $query)){
            $posts = mysqli_fetch_array($result);
        }
    }
?>

如果你想显示结果,你可以试试这个代码。

<?php echo $posts['get-slug']; ?>