Reputation: 25
I am using eloquent relationships for post
and tags
through post_tags
. What i'm trying to do is make sections of posts
in my front-end view with specific tags
. Like if i have a section 1
it should have all posts of tag "new"
, section 2
should have all posts of tag "old"
etc. And i want all of this to happen in a same view.
Post Model
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag');
}
Tag Model
public function posts()
{
return $this->belongsToMany('App\Post', 'post_tag');
}
Controller
public function index()
{
$posts = Post::all();
return view('frontend.index')->withPosts($posts);
}
Please help me out:)
Upvotes: 2
Views: 2922
Reputation: 11083
You can get all the tags with loading the posts :
public function index()
{
$tags = Tag::with('posts')->get();
return view('frontend.index')->withTags($tags);
}
In the view you can do something like this :
@foreach ($tags as $tag)
<h2>Tag : {{ $tag->name }}</h2>
@foreach ($tag->posts as $post)
<p>Post : {{ $post->title }}</p>
@endforeach
@endforeach
For geting the posts where you have a tag :
public function index()
{
$tagName = 'new';
$posts = Post::whereHas('tags', function ($q) use($tagName) {
$q->where('name', $tagName);
})->get();
return view('frontend.index')->withTagName($tagName)->withPosts($posts);
}
And in the view you can do this :
<h2>Tag : {{ $tagName }}</h2>
@foreach ($posts as $post)
<p>Post : {{ $post->title }}</p>
@endforeach
If you want to do queries from view you can do it like this (but it's not a god practice because the view is just for viewing the content not geting it from database) :
<?php foreach ((\App\Post::whereHas('tags', function ($q) use($tagName) {
$q->where('name', $tagName);
})->get()) as $post) { ?>
<p>Post : {{ $post->title }}</p>
<?php } ?>
Upvotes: 2
Reputation: 47
It is solution not perfect answer
You can handle this situation in two ways
1- send two objects from controller to view seprate one for only new tag and second without new tag
2- you can handle this situation in front-end by using conditions
@if($user->tag == "new")
{$user->show}
@endif
Upvotes: 0
Reputation: 163798
To get all posts with tags with name new
, do this:
Post::whereHas('tags', function ($q) {
$q->where('name', 'new');
})->get();
Upvotes: 2