简体   繁体   中英

Laravel paginate redirect back, if page does not exist

I have situation. I have products in wishlist and I have action: "remove" with ajax.
And I have pagination:

$wishlists = Wishlist::with('product')->where('user_id', $profile->id)
             ->orderby('id', 'desc')->paginate(3);

Initially I have 2 pages on pagination.
When I remove items from wish list, In pagination I have 1 page, but on page I have 2 pages on pagination, because I use ajax. How I can check, if user moved on page, which does not exist on pagination and redirect him on first page pagination?

before query you can check total pages

$totalRecords = Wishlist::with('product')->where('user_id', $profile->id)
             ->count();

$totalPage = $totalRecords/10; (where 10 is records per page)

now you check

$ajaxpage = 3;
if($totalPage < $ajaxpage){
    $ajaxpage = 1;(get last page)
}
$wishlists = Wishlist::with('product')->where('user_id', $profile->id)
             ->orderby('id', 'desc')->paginate($ajaxpage);

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