CEO ASH
CEO ASH

Reputation: 55

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

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

public function postCategory()
{   
    return $this->belongsTo('App\PostCategory');
}

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

Upvotes: 0

Views: 1079

Answers (1)

liqSTAR
liqSTAR

Reputation: 1335

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:

return $this->hasMany('App\Post', 'post_category_id','post_category_id');

Upvotes: 0

Related Questions