Home > Back-end >  How to create pagination in laravel when my custom query like How to use this result in predesign we
How to create pagination in laravel when my custom query like How to use this result in predesign we

Time:06-11

// blog list page
    public function blogs(Request $request)
    {
        $perPage = 10;
        $offset = 0;
        $page = $request->has("page")?$request->page:1;

        if($page > 1){
            $offset = ($page - 1)*$perPage;
        }
        $blogs = Blog::where(['status' => 1])->offset($offset)->limit($perPage)->get();
        return view('frontend.blog', ['blogs' => $blogs]);
    }

Here my query to get data in with perpage and page number. How to use it frontend.

CodePudding user response:

you can use in this code for get data with pagination with per_page

use this code into in your model

public function getPerPage()
{
    return request('per_page');
}

and for get data models with pagination

Blog::where(['status' => 1])->paginate();

CodePudding user response:

Laravel does it for you: https://laravel.com/docs/9.x/pagination#basic-usage

You only need to be sure to send the page query string argument in your url.

So your code should look like this:

public function blogs(Request $request)
    {
        $perPage = 10;
        $blogs = Blog::where(['status' => 1])->paginate($perPage);
        return view('frontend.blog', ['blogs' => $blogs]);
    }
  • Related