skip to Main Content

I want to get previous and next news order by date. The code below works fine if there is only one news a day. But cannot handle multiple news on the same day.

NewsController.php

public function detail($slug){
    $news = AppNews::active()->where('slug', $slug)->firstOrFail();
    
    $prev_news = AppNews::whereDate('date', '>', $news->date)->active()->orderBy('date', 'desc')->first();
    
    $next_news = AppNews::whereDate('date', '<', $news->date)->active()->orderBy('date', 'desc')->first();
}

web.php

 Route::get('/news/{slug}', 'NewsController@detail')->name('news');

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution:

    $news = AppNews::active()->where('slug', $slug)->firstOrFail();
    
    $prev_news = AppNews::withDescription()->where(function($query) use($news){
        $query->where(function($query) use($news){
            $query->whereDate('date', $news->date)->where('id', '<', $news->id);
        })->orWhereDate('date', '>', $news->date);
    })->online()->orderBy('date', 'asc')->orderBy('id', 'desc')->active()->first();
    
    $next_news = AppNews::withDescription()->where(function($query) use($news){
        $query->where(function($query) use($news){
            $query->whereDate('date', $news->date)->where('id', '>', $news->id);
        })->orWhereDate('date', '<', $news->date);
    })->online()->orderBy('date', 'desc')->orderBy('id', 'asc')->active()->first();
    

  2. $prev_news = $news->whereDate('date', '>', $news->date)->active()->orderBy('date', 'desc')->get();
    
    $next_news = $news->whereDate('date', '<', $news->date)->active()->orderBy('date', 'desc')->get();
    

    you used ->first();
    this only returns 1 value. so change it up to get()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search