Search code examples
phplaravellaravel-5laravel-routinglaravel-blade

Display Category Slug in URL Instead of ID


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


Solution

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