CEO ASH
CEO ASH

Reputation: 55

Trying to retrieve posts from table by category slug

Hello i am trying to loop posts that are associated to each category by the slug. It works when i use the ids but when i change my controller function to search by slug it retrieves the slug but does not load the foreach loop.

I have tried so many methods and i don't know where i am going wrong please help.

Category Model :

protected $table = 'post_categories';
public function posts()
{
    return $this->hasMany('App\Post', 'id', 'name', 'catslug');
}

Post Model

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

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

Controller

public function getPostCategory($catslug) {        
    $postCategories = PostCategory::with('posts')
                    ->orderBy('name', 'asc')
                    ->where('catslug', '=', $catslug)
                    ->first();
     return view ('articles.category.categoriesposts')->with('postCategories', $postCategories);
}

Route

Route::get('articles/category/{catslug}',  [ 
 'uses'  =>  'ArticlesController@getPostCategory' ,
 'as'    =>  'PostCategory'
] );

View

@foreach($postCategories->posts as $post)
  <h4>{{ substr($post->title, 0, 50) }}</h4>
   <p>{{ substr($post->body, 0, 90) }}</p>             
 @endforeach

When i use id there is no problem i cant see what i am doing wrong any feedback will be truly appreciated

Thanks

Ash

Upvotes: 1

Views: 122

Answers (1)

Dhruv Raval
Dhruv Raval

Reputation: 1583

Save category id in posts table insted of category name or slug.

Change in post category model:

public function posts()
    {
        return $this->hasMany('App\Post', 'category_id');
    }

Your controller method:

public function getPostCategory($catslug)
    {
        $postCategories = PostCategory::with('posts')->where('catslug', $catslug)->first();
        return view('articles.category.categoriesposts')->with('postCategories', $postCategories);
    }

If you want to order posts by name then add orderBy() in relationship :

public function posts()
    {
        return $this->hasMany('App\Post', 'category_id')->orderBy('name', 'asc');
    }

Upvotes: 0

Related Questions