laravel で 前後のページ、及びレコードを取得したい場合がある。
その時の書き方。
$next = Article::query()//単数形 User
->where('id','>',$request->id)
->orderBy('id','ASC')
//NGユーザーは読み出さない
->whereDoesntHave('social', function ($q){
$q->where('ng',1);
})
->select('id','name')
->first();//最初の
//次ページある
if (!empty($next->id)) {
pd($next->id);
pd($next->name);
} else {
pd("次ページはありません");
}
$prev = Article::query()//単数形 User
->where('id','<',$request->id)
->orderBy('id','DESC')
//NGユーザーは読み出さない
->whereDoesntHave('social', function ($q){
$q->where('ng',1);
})
->select('id','name')
->first();//最初の
//次ページある
if (!empty($prev->id)) {
pd($prev->id);
pd($prev->name);
} else {
pd("前ページはありません");
}
こんな感じ。