Tuesday 24 December 2019

Pagination in Laravel 6 with Next And Previous Button using Ajax



If you want to make Pagination in Laravel 6 on with Next and Previous Button Link, then this tutorial is for you. In this post, you can learn How to make Pagination only with Next and Previous Button Link in Laravel using Ajax. Here we will create customize next and previous pagination link in Laravel 6 framework using Ajax.

As Web Developer, we have know Pagination is a one type of design pattern, which has been widely used in most of web site of displaying content on web page. Pagination is a method of dividing large amount of content into different small piece and display large data into small pieces on web page, and suppose user want to view more data, then by using navigation option it can view next part of web content on web page.

There are different way we can use pagination in our web application. Some web developer has use divide content into different page number with navigation link for go to that page number content, some has use drop down list with option of page number, User has to select page number and he can go to data of that web page. And some one has use previous and next page link for go to next or previous page link. So, there is many different ways we can use pagination feature in our web application.

In this tutorial, we will make pagination with next and previous button link in Laravel 6 framework using Ajax. Laravel 6 framework has inbuilt pagination library for make pagination link. But here we want to add next and previous button link in pagination, For this here we can use simplePaginate() method in Laravel 6 framework. By using this eloquent simplePagiante() method we can add simple pagination with only previous and next button link.

But we want to provide more user experience in Laravel 6 pagination. So here we have use also use Ajax web technology. By using Ajax with Laravel 6 pagination, next and previous page data will be load without refresh of web page. So, if you are willing to add pagination with next and previous button link in Laravel 6 using Ajax, then you have to follow below step.




  1. Install Laravel 6 framework

  2. Make Database Connection

  3. Create Controller

  4. Create View Blade File

  5. Set Route

  6. Run Laravel Application


Install Laravel 6 framework


If want to developed application in Laravel, so first we want to download Laravel 6 framework and install in our local computer.

For this we have to go command prompt, and then after go to directoy in which we want to download and install this framwork and run following command.


composer create-project --prefer-dist laravel/laravel laravel6


Make Database Connection


Once Laravel framework has been install in define directory, first we want to make database connection. For this we have open .env file and in this file we have to define Mysql database configuration, which you can find below and it will make database connection.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


After making database connection, now we have to make one table with some data in Mysql database. For this you have to run following sql script. It will make table with some sample data in Mysql database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_datas`
--

CREATE TABLE `sample_datas` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `sample_datas`
--

INSERT INTO `sample_datas` (`id`, `first_name`, `last_name`, `created_at`, `updated_at`) VALUES
(1, 'John', 'Smith', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(2, 'Peter', 'Parker', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(3, 'Larry', 'Degraw', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(5, 'Susan', 'Diener', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(6, 'William', 'Batiste', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(7, 'Butler', 'Tucker', '2019-10-14 00:30:00', '2019-10-19 03:24:32'),
(8, 'Eva', 'King', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(9, 'Dorothy', 'Hays', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(10, 'Nannie', 'Ayers', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(11, 'Gerald', 'Brown', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(12, 'Judith', 'Smith', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(14, 'Delores', 'Schumacher', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(15, 'Gloria', 'Romero', '2019-10-14 06:30:00', '2019-10-14 06:30:00'),
(17, 'Paul', 'Pate', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(18, 'Ryan', 'Hoang', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(19, 'Dixie', 'Smith', '2019-10-17 06:52:21', '2019-10-17 06:52:21'),
(20, 'Jack', 'Smith', '2019-10-17 23:22:30', '2019-10-19 00:39:56'),
(22, 'Ronald', 'Derby', '2019-10-18 00:00:01', '2019-10-18 00:00:01');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_datas`
--
ALTER TABLE `sample_datas`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_datas`
--
ALTER TABLE `sample_datas`
  MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;




Create Controller


In Laravel framework, for handle http request we have to make controller class. For this we have to command prompt and run following command.


php artisan make:controller PaginationController


This command will make PaginationController.php file in app/Http/Controllers folder. In this class first we have to add use DB; statement, by using this statement we can use Laravel query builder class for database related operation. In this class we have make following method.
  • index() - This is the root method of this class. This method will fetch five data from Mysql table. And then after it will load that data in pagination_parent.blade.php view file.
  • fetch(Request $request) - This method will received Ajax request for fetch next five data from Mysql table. Here we have use simplePaginate() method for make pagination with Next and Previous button link. And lastly it will load data in pagination_child.blade.php file.

app/Http/Controllers/PaginationController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class PaginationController extends Controller
{
    function index()
    {
     $data = DB::table('sample_datas')->simplePaginate(5);
        return view('pagination_parent', compact('data'));
    }

    function fetch(Request $request)
    {
     if($request->ajax())
     {
      $data = DB::table('sample_datas')->simplePaginate(5);
         return view('pagination_child', compact('data'))->render();
     }
    }
}
?>


Create View Blade File


For display output in the form of HTML, In Laravel we have to create view blade file. In Laravel view file has been use blade templating engine for convert output in HTML format and view file has been store under resources/views folder.Here we have make following view file.

resources/views/pagination_parent.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 6 Pagination with Next Previous Button Link using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 6 Pagination with Previous Next Button Link using Ajax</h3>
     <br />
     @csrf
     <div class="table-responsive" id="table_data">
    @include('pagination_child')
   </div>
        </div>
 </body>
</html>


<script>
$(document).ready(function(){

 $(document).on('click', '.page-link', function(event){
    event.preventDefault(); 
    var page = $(this).attr('href').split('page=')[1];
    fetch_data(page);
 });

 function fetch_data(page)
 {
  var _token = $("input[name=_token]").val();
  $.ajax({
      url:"{{ route('pagination.fetch') }}",
      method:"POST",
      data:{_token:_token, page:page},
      success:function(data)
      {
       $('#table_data').html(data);
      }
    });
 }

});
</script>




resources/views/pagination_child.blade.php

<div class="table-responsive">
    <table class="table table-striped table-bordered">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        @foreach($data as $row)
        <tr>
            <td>{{ $row->first_name }}</td>
            <td>{{ $row->last_name }}</td>
        </tr>
        @endforeach
    </table>

    {!! $data->links() !!}
</div>


Set Route


In Laravel we have to set the route of controller method for display result on web page. For this we have to open routes/web.php file and in this file we have to define route.

routes/web.php

<?php

Route::get('/pagination', 'PaginationController@index');

Route::post('pagination/fetch', 'PaginationController@fetch')->name('pagination.fetch');

?>


Run Laravel Application


Once all code is ready, now we want to run Laravel application. For this first we have to go command prompt and run following command.


php artisan serve


This command will run Laravel server and provide use base url of laravel application. For test above code you have to run following url in your browser.


http://127.0.0.1:8000/pagination


So, this is step by step process for creating Pagination with Next and Previous button link in Laravel 6 using Ajax. So, We hope this tutorial will help you to learn this topic.

1 comment:

  1. Call to a member function links() on string (View: D:\Internship\internship\resources\views\admin\dashboard\display.blade.php)

    ReplyDelete