Home > Blockchain >  Laravel - whereHas and whereHas
Laravel - whereHas and whereHas

Time:12-25

I need to get the posts where the post has tag1 AND tag2 (or more)

I've tried this:

$posts = Post::whereHas('tags', function(Builder $query) {
    foreach (request('tags') as $tag) { // request('tags') = integer array
        $query->where('id', $tag);
    }
})->get();

But it doesn't work.

CodePudding user response:

If you really want to get post where has tag1 AND tag2 you can do with below code

$posts = Post::query();
foreach (request('tags') as $tag) { // request('tags') = integer array
    $posts = $posts->whereHas('tags', function(Builder $query) use ($tag) {
        $query->where('id', $tag);
    });
}
$posts = $posts->get();

But if you meant want to get posts where has tag1 OR tag2.

You can use whereIn method:

$posts = Post::whereHas('tags', function(Builder $query) {
    $query->whereIn('id', request('tags'));
})->get();

or alternative use orWhere

$posts = Post::whereHas('tags', function(Builder $query) {
    foreach (request('tags') as $tag) { // request('tags') = integer array
        $query->orWhere('id', $tag);
    }
})->get();
  • Related