简体   繁体   中英

How do I exclude a specific row in Laravel?

I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

$finalNews = News::find(DB::table('news')->max('id'));

But than I have another variable which return all the rows from News table with the following code

$news = News::orderBy('id','desc')->get();

I want to exclude the news row which is equal to $finalNews at the end of controller I return view with following data

return view('news', ['news' => $news, 'finalNews' => $finalNews]);

How can I exclude the last news? I am using Laravel and MySQL.

Try to use following code

$finalNews = News::find(DB::table('news')->max('id'));

$news = News::where('id','<>',$finalNews->id)->orderBy('id','desc')->get();

Exclude the Id of latest news from the news list

$finalNews = News::find(DB::table('news')->max('id'));

$latestId = $finalNews->id;

$news = News::where('id','!=',$latestId)
        ->orderBy('id','desc')
        ->get();

First, get all news

$news = News::orderBy('id','desc')->get();

Then, pop the last item (the lastest news) out of $news

$latest_news = $news->pop();

https://laravel.com/docs/5.5/collections#method-pop

There is no need to use 2 queries in this case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM