How to display all the posts from categories?

Hello. Conventionally, there are positions, there are categories. Implemented the one-to-many relationship. As you can now through the post to the category?
class Tag extends Model
{
 public function recipes() {
 return $this->hasMany('App\Recipe');
}
}

class Recipe extends Model
{
 public function tags()
{
 return $this->'s belongsto('App\Tag');
 }

$posts = Recipe::with('tags')->get();
@foreach($recipes as $recipe)
$recipe->tags->name //so can't get the category name of this post, what am I doing wrong?
 @endforeach
July 2nd 19 at 17:37
1 answer
July 2nd 19 at 17:39
Solution
Not quite clear structure used to reference tags to the content.

Implement the following architecture:
6bea3a74a58e446dbba5b26c00e3a7b9.png
class Recipe extends Model
{
 public function tag_links()
{
 return $this->hasMany('Recipe_Tag', 'recipe_id');
}
}

class Model extends Recipe_Tag
{
 public function tag()
{
 return $this->hasOne('Tag', 'tag_id');
}
}

class Tag extends Model
{
}

Usage:

$receipes = Recipe::with('tag_links')->get();
foreach ($receipes as $receipe)
{
 echo '<h1>'.$receipe->title.'</h1>';
 echo 'Category: ';
 foreach ($receipe->tag_links as $tag_link)
{
 echo $tag_link->tag->name;
}
}

The advantage of this approach do not have to explain.

P. S. Example using controller - provided for clarity.

Udachki! ;-)
Horror. Why are there 2 cycle. Theme tagged with Laravel. - Arthur_McCullough70 commented on July 2nd 19 at 17:42
: To handle the output of each individual category, no? Changed the code for the actual output of news, so it became clearer? - Buddy commented on July 2nd 19 at 17:45
: Tag and nothing need? Not getting for some reason the name tag.. - tiana.Kihn commented on July 2nd 19 at 17:48
: What writes? - Buddy commented on July 2nd 19 at 17:51
: Nothing, just does not display. If you just write $tag then get the array ID is all true, how-only $tag->name does not output Anything - tiana.Kihn commented on July 2nd 19 at 17:54
: Fixed. - Buddy commented on July 2nd 19 at 17:57
: Thank you. edit, maybe someone will need
$posts = Recipe::with('tag_links')->get();
public function tag()
{
return $this->hasOne('App\Tag', 'id', 'tag_id');
} - tiana.Kihn commented on July 2nd 19 at 18:00

Find more questions by tags Laravel