Question: How to search all articles belongs to a tag in laravel

Question

How to search all articles belongs to a tag in laravel

Answers 3
Added at 2016-12-29 03:12
Tags
Question

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.

Answers to

How to search all articles belongs to a tag in laravel

nr: #1 dodano: 2016-12-29 04:12

Using whereHas()

 $articles=Article::whereHas('tags',function($query)
        {
            $query->where('name',$name);
        })->get();
nr: #2 dodano: 2016-12-29 04:12

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

nr: #3 dodano: 2016-12-29 04:12

Use eager loading:

$tags = $this->tag->where('name', $name)->with('articles')->first();

This code will load tag with all it's articles.

Source Show
◀ Wstecz