php - Get all the data with specific tag in laravel

529

I am using eloquent relationships for{-code-1} and{-code-2} through{-code-1}_{-code-2}. What i'm trying to do is make sections of{-code-1}s in my front-end view with specific{-code-2}. Like if i have a section1 it should have all {-code-1}s of tag"new", section2 should have all {-code-1}s of tag"old" etc. And i want all of this to happen in a same view.

Post Model

public function {-code-2}()
{
    return $this->belongsToMany('App\Tag', '{-code-1}_tag');
}

Tag Model

 public function {-code-1}s()
 {
     return $this->belongsToMany('App\Post', '{-code-1}_tag');
 }

Controller

public function index()
{
    ${-code-1}s = Post::all();
    return view('frontend.index')->withPosts(${-code-1}s);    
}

Please help me out:)

403

Answer

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

Answer

Solution:

To get all posts with tags with namenew, do this:

Post::whereHas('tags', function ($q) {
    $q->where('name', 'new');
})->get();
394

Answer

Solution:

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

People are also looking for solutions to the problem: php - what a correct statement for this code?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.