Показывать категорию Slug в URL вместо ID - PullRequest
0 голосов
/ 11 декабря 2018

Я относительно новичок в Laravel, и я застрял, пытаясь отобразить слаг-категории вместо идентификатора.

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

Мой сайт в настоящее время показывает www.website/.../category-Я бы.У меня есть таблица категорий и таблица сообщений с колонками.

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

Я перепробовал много методов, но, похоже, ничего не работает.Любая помощь будет оценена.

Большое спасибо,

Ясень

Ответы [ 2 ]

0 голосов
/ 11 декабря 2018

Это должно работать для вас:

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


}
0 голосов
/ 11 декабря 2018

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