Skip to content
Advertisement

Laravel skip results if they are found in previous query

I’m querying my DB twice to get some items into the header of the page and some bellow the header. I want to avoid duplicates in these two queries, currently I do this by adding a skip method to everything bellow the header. But I’m sure that I’m skipping some items altogether when doing this because I have 10 queries bellow the headernews and each of them are skipping 5 items while the header news are only taking the 5 newest items.

Is there a better way to avoid duplicates in these two queries?

$headerNews = News::orderBy('date','DESC')
->whereNotIn('portal', $notwantedTop3)
->take(10)
->get();

$bigSmallNews = News::orderBy('date','DESC')
->where(function($query) {
    $query->where('news_category','Bignews')
    ->orWhere('news_category', 'Smallnews')
})
->skip(5)

Advertisement

Answer

$bigSmallNews = News::orderBy('date','DESC')
    ->where(function($query) {
        $query->where('news_category','Bignews')
            ->orWhere('news_category', 'Smallnews')
    })
    ->whereNotIn('id', $headerNews->pluck('id'))->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement