I have a Posts
table it has three fields id
, title
, description
.
My Post
Model
class Post extends Model
{
use SoftDeletes;
protected $fillable = ['title', 'description'];
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag');
}
}
My Tag
Model
class Tag extends Model
{
use SoftDeletes;
protected $fillable = ['name'];
public function posts()
{
return $this->belongsToMany(Post::class, 'post_tag');
}
}
Now I want to get posts & paginate where I have a tag filter e.g I have two tags animals
& news
which has id 1
& 2
. Now I want to get all posts which has tag 1
& 2
& paginate
. Here is what I tried
Post:: with('tags')->whereHas('tags', function($q) {
$q->whereIn('id', [1, 2]);
})->paginate();
But here as I am whereIn
it returns posts has tags 1
or 2
or both
. But I want post who has both tag id 1 & 2.
I am using Laravel 5.2
.