ChenLee
ChenLee

Reputation: 1499

How to search all articles belongs to a tag in laravel

Article Model

class Article {
    public function Tag(){
      return $this->belongsToMany('App\Tag');
    }
}

Tag Model

class Tag {
    public function Article(){
      return $this->belongsToMany('App\Article');
    }
}

Pivot Table

article_id === tag_id

I want to search all books use a tag's name. How can I do this?

My Solution

public function tagArticle($name)
{
    $tags = $this->tag->where('name',$name)->get();
    $articles = [];
    foreach ($tags as $tag) {
        $articles[] = $tag->articles;
    }
    return view('front.home')->with('articles',$articles);
}

This is my solution, but I don't think it's good. Does anyone has other solutions? Thank you.

Upvotes: 4

Views: 949

Answers (2)

xmhafiz
xmhafiz

Reputation: 3538

Use map with flatten would be better.

$tags = $this->tag->where('name',$name)->get();

$articles = $tags->map(function($v) { 
    return $v->articles; 
})
->flatten()
->all();

The flatten will return all articles in the same level

[
   articleObject,
   articleObject,
   articleObject,
]

More detail https://laravel.com/docs/5.3/collections#method-map

Upvotes: 1

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

Using whereHas()

 $articles=Article::whereHas('tags',function($query)
        {
            $query->where('name',$name);
        })->get();

Upvotes: 2

Related Questions