Hello World, Today i am going to create pagination in laravel. In this laravel tutorial, we will implement simple bootstrap 4 style pagination. For this example, i will extends my previous tutorial in which i have implemented ajax working in laravel.
I have divided this tutorial into following parts:
- Fetch data according to pagination in controller
- Setup route for showing all data
- Create template to show data with pagination
Fetch data according to pagination in controller
In this step, we will add following method in PostController. In this method, paginate method will return data with some specific parameters which is require to show pagination.
// Show all posts with pagination function all_posts(){ $posts=Post::paginate(5); return view('all-post',['posts'=>$posts]); }
Setup route for showing all data
Add the following code in /routes/web.php.
// All Posts Route::get('all-post','PostController@all_posts');
Create template to show data with pagination
In this step, we will create a template which will show all data with pagination links.
- Create /resources/views/all-post.blade.php file and add the following code in it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Create pagination with laravel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="container mt-4"> {{ $posts->links() }} <div class="mt-4"> @if(count($posts)>0) @foreach($posts as $data) <div class="border p-3 mb-4 shadow-sm"> <h3 class="border-bottom pb-2"><a href="{{ url('post-detail/'.$data->id) }}">{{ $data->title }}</a></h3> <p>{{ $data->body }}</p> </div> @endforeach @else <p class="bg-light p-2 border"><strong class="text-warning">No Data Found!!</strong></p> @endif </div> </div> </body> </html>
In the above code, $posts->links creates pagination links.
I hope you are enjoying my tutorials. Please add your feedback in the comment section. Thank you. 🙂 🙂