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

I'm relatively new to Laravel, and I have found myself stuck trying to display category slugs instead of the ID.

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

My website currently shows www.website/.../category-id. I have a categories table and a posts table with columns.

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

post_categories table = | id | name | catslug |

Controller

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

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

I've tried many methods, but nothing seems to work. Any help would be appreciated.

Many thanks,

Ash

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'
] );

That's it. Also, you can minify your route code:

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

This should work for you:

**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);


}