I want to show my categories at each of my posts,
So far I have tried the following:
@if(isset($post->category->name_slug))
{{ action('PagesController@showCategory', ['id' => $post->category
>name_slug ]) }} {{ $post->category->name }}
@endif
but still no result, any idea?
In order to display all categories of your post you just need to loop through the categories of the post like so :
I updated my code according to the change in your question
// post here refers to the current post you are displaying
// so this loop may be contained inside another loop that displays the posts
{{ $post->category->name }}
from the code you posted above, I doubt that you named your relationship in the Post
model correctly, because it should be categories
and not category
In your Post.php
model set up the relationship to a category
public function category() {
return $this->belongsTo(App\Category::class);
}
In your Category.php
model, set up the relationship to many posts
public function posts() {
return $this->hasMany(App\Post::class);
}
Now, as long as your posts
table has a category_id
column, you can call on these relationships.
Category: {{ $post->category->name }}
And of course, if you want to, say, list all the posts in a certain category:
foreach($category->posts as $post) {
// do something here
}
If a post can have many categories, you need to set up a pivot table. posts
, category_post
, categories
On your category_post
pivot table you have: post_id
, category_id
This relationship is defined in your Post.php
model like this:
public funtion categories() {
return $this->belongsToMany(App\Category::class, 'category_post');
}
And to call this, of course you use the relationship like this:
Categories:
foreach($post->categories as $category) {
{{ $category->name }}
}