1
votes

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

1
as i understand you need post based on category slug okay? - Dhruv Raval
Yes that is exactly what i need.. where am i going wrong? - CEO ASH
wait i will add asnwer give minutes. - Dhruv Raval

1 Answers

0
votes

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');
    }