[英]Display posts belonging to category in laravel
I am trying to get the posts that belong to each category, i had this working before but i can't seem to find what i have done wrong here. 我正在尝试获取属于每个类别的帖子,我之前有这个工作,但我似乎无法找到我在这里做错了什么。
I have a Post Table and a Categories Table 我有一个帖子表和一个类别表
ROUTE 路线
Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController@getPostCategory']);
CONTROLLER CONTROLLER
public function getPostCategory($id)
{
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
$categories = PostCategory::all();
// return view
return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}
VIEW 视图
@foreach($postCategories->posts as $post)
<div class="well">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placekitten.com/150/150">
</a>
<div class="media-body">
<h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
<p class="text-right">By Francisco</p>
<p>{{ substr($post->body, 0, 90) }}</p>
<ul class="list-inline list-unstyled">
</ul>
</div>
</div>
</div>
@endforeach
POST MODAL POST MODAL
public function postCategory()
{
return $this->belongsTo('App\PostCategory');
}
POSTCATEGORY MODAL POSTCATEGORY MODAL
class PostCategory extends Model
{
// connect Categories to Posts tables
protected $table = 'post_categories';
// Category belongs to more than 1 post
public function posts()
{
return $this->hasMany('App\Post', 'post_category_id');
}
}
I can't see what i am doing wrong every time I go to a category it shows 每次我去看它所展示的类别时,我都看不出我做错了什么
Trying to get property of non-object 试图获得非对象的属性
Any help will be much appreciated thanks 任何帮助将非常感谢谢谢
replace your lines: 替换你的线:
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
with: 有:
$postCategories = PostCategory::find($id)->posts;
Change your line in your PostCategoryModel to: 将PostCategoryModel中的行更改为:
return $this->hasMany('App\Post', 'post_category_id','post_category_id');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.