我不是Laravel的新手,我发现自己一直想显示类别标签而不是ID。
eg: www.website/.../category-slug
我的网站当前显示www.website/.../category-id。我有一个类别表和一个带有列的帖子表。
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'
]);
我尝试了很多方法,但是似乎没有任何效果。任何帮助将不胜感激。
非常感谢,
灰
答案 0 :(得分:0)
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');
答案 1 :(得分:0)
这应该对您有用:
**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);
}
答案 2 :(得分:0)
您可以尝试以下方法:
<?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']; ?>