Wednesday, January 22, 2020

Laravel 6 Pagination with Next And Previous Button using Ajax

Laravel 6 Pagination with Next And Previous Button using Ajax

If you want to paginate with the "Next" and "Back" buttons in Laravel 6, this tutorial is for you. In this post, you'll learn how to use Ajax to paginate using the next and previous link buttons in Laravel. Here we use Ajax to create a personalized link to the next and previous pagination as part of Laravel 6.

As web developers, we know that pagination is a kind of design pattern that is commonly used on most websites to display content on the website. Pagination is a method of dividing a large amount of content into different small parts and displaying large data on the website in small parts. Assuming the user wants to see more data, you can use the navigation option to see the following part of the web content on the website.

There are several ways we can use pagination in our web application. Some web developers have divided the content into another page number with a navigation link to get to the content of the page number, others have used the drop-down list with the page number option. The user must select the number of pages page and you can go to the data on this website. And someone used the link on the previous and next page to go to the link on the next or previous page. Therefore, there are many different ways that we can use the paging function in our web application.

In this tutorial we will use Ajax to create a pagination with the link of the next and previous button in Laravel 6. The Laravel 6 framework has an integrated paging library to establish a paging connection. But here we want to insert the link of the next and previous button into the pagination, for this we can use the simplePaginate () method in the context of Laravel 6. With this eloquent simple methodPagiant () we can only insert simple pagination with the button link Previous and Next.

However, since we want to offer more user experience in Laravel 6 pagination, we also use Ajax web technology here. If you use Ajax with Laravel 6 pagination, the data is loaded on the next and previous page without the website being updated. So if you're ready to add pagination using the link to the next and previous button in Laravel 6 using Ajax, you'll need to do the next step.


1.     Install Laravel 6 framework by commond line

2.     Create Database Connection

3.     Build Controller

4.     Build View Blade File

5.     Set Route

6.     Run Laravel App



Install Laravel 6 framework by commond line 

If we want to develop an application in Laravel, we first want to download the Laravel 6 framework and install it on our local computer.

To do this, we have to go to the command prompt and then go to the directory where we want to download and install this framework and run the following command.


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

Create Database Connection

After the Laravel Framework has been installed in the define directory, we would first like to establish the database connection. For this we opened the .env file and in this file we have to define the configuration of the MySQL database, which you can find below, and establish the database connection.


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


After connecting to the database, we now need to create a table with some data in the MySQL database. To do this, you need to run the following SQL script. A table with some sample data is created in the 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;




Build Controller


As part of Laravel, we need to run the controller class to handle the http request. To do this, we need to request the command prompt and run the following command.


php artisan make:controller PaginationController

This command creates the PaginationController.php file in the app / Http / Controllers folder. In this class we have to add use DB first; With this statement, we can use the Laravel query generator class for the operation that is related to the database. In this class we have to do the following method.


  • index (): This is the root method of this class. This method retrieves five data from the mysql table. This data is then loaded into the view file pagination_parent.blade.php.
  • fetch (Request $ request): This method receives the Ajax request to retrieve the following five data from the MySQL table. Here we have used the simplePaginate () method for pagination with the linking of the Next and Previous buttons. Finally data is loaded into the file pagination_child.blade.php.


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();
     }
    }
}
?>


 

Build View Blade File


To view the output in HTML form, you must create a view blade file in Laravel. In the Laravel view file, the knife template engine converted the output to HTML and the view file was saved in the resources / views folder. Here we have the 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 And Previous Button 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 Next And Previous Button 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 path of the controller method to display the result on the website. To do this, we have to open the routes / web.php file and define the route in this file.

routes/web.php


<?php

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

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

?>



Run Laravel App


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


php artisan serve


This command runs the Laravel server and provides the use of the base URL of the Laravel application. To test the code above, you need to run the following URL in your browser.


http://127.0.0.1:8000/pagination

So this is a step-by-step process to create a pagination using the Next and Previous buttons in laravel 6 using Ajax. For this reason, we hope that this tutorial will help you learn this topic.

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.