2016-08-30 125 views
0

對於博客站點,我有所有文章&類別列表顯示在一個頁面上,但現在我需要在它自己的單獨頁面上顯示每個類別的文章。Laravel - 按ID顯示類別

比方說,我有一個分類是'Javascript',我只想要在頁面上顯示javascript類別的帖子。

這是做什麼正確的代碼?這裏有一個例子,粗體的'javascript'是需要用正確的代碼替換的。

- categoriesController.php ---

public function show($id) 
{ 
$post->withCategories($Categories)->$id->($id as **javascript)** 
} 

--- --- javascript.blade.php(對應圖)

<tbody> 
@foreach ($categories as $category->$id>**javascript**) 
<tr> 
<th>{{ $category->id }}</th> 
<td>{{ $category->name }}</td> 
</tr> 
@endforeach 
</tbody> 
</table> 
</div> <!-- end of .col 
+0

更新代碼一部分,包括'info'的評論不是一個代碼。共享代碼你有什麼 – C2486

+0

可能是你應該有'$ category'而不是'$ category - > $ id'在foreach – C2486

+0

目前我有 - @ foreach($ categories作爲$ category) 但是這顯示所有類別不只是一個。我是Laravel的新手,但我認爲還有其他的東西需要更多的獲取每一個 – n31l

回答

1

例如: post.php中模型 class Post延伸Model { protected $ primaryKey ='id';

function withCategories() { 
     return $this->hasOne('App\Categories', 'id', 'category_id'); 
    } 

    public function show($id){ 
     Post::with('withCategories')->where('category_id', $id)->get(); //the output of articles of the category 
    } 
} 

$ id爲URL的參數:site.com/posts/javascript

在posts.blade.php

<table> 
<tbody> 
@foreach ($posts as $post) 
<tr> 
<th>{{ $post->id }}</th> 
<td>{{ $post->name }}</td> 
<td>{{ $post->withCategories->name }}</td> <!-- Category name--> 
</tr> 
@endforeach 
</tbody> 
</table> 
</div> 
+0

謝謝,所以在更新category.php模型之後,使用下面的代碼 '<?php namespace App; 使用Illuminate \ Database \ Eloquent \ Model; class category extends Model { protected $ table ='categories'; 公共職位帖子() { \t return $ this-> hasMany('App \ Post'); } function withCategories(){ return $ this-> hasOne('App \ Categories','id','category_id'); ('withCategories') - >其中('category_id',$ id) - > get(); } } }' 這就是我需要的嗎? – n31l

+0

不會更新category.php模型。 article.php模型的示例代碼 –