Search code examples
phplaravellaravel-5tagslaravel-5.3

Get all the data with specific tag in laravel


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:)


Solution

  • 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 } ?>