Showing posts with label laravel pagination ajax. Show all posts
Showing posts with label laravel pagination ajax. Show all posts

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.

Friday, 22 February 2019

Ajax jQuery Load More Data in Laravel



If you have seen any social media sites like Youtube, Twitter or Facebook, in which when page has been load then it has not load all data on web page, when it was load in browser. But in all those sites they have load only last some data on web page, and suppose we want to view more data, then we have to click on load more button. So, this types of techniques we have to implement in Laravel by using ajax jQuery. In this features data will be load dynamically, when user have been click on button, and here it will make pagination without displaying links to user.

Load More or Show More functionality is very simple and user friendly, this is because here all data has not been load at the same time, but it will load only after click on button like pagination, but also it will load more data without refreshing of web page. In this post we will make this type of feature like Load more data from Mysql Database using Ajax in Laravel Framework.

There are two type of load more data feature, one is when user has been click on button then next records has been load on web page, and other is when page has been scroll then next data has been load on web page. But here we will implement load more data on button click event, which we will make in Laravel framework using Ajax jQuery. It will works in a very simple way, and when page has been load then it will load some specific number of data, Suppose we want to view next records, then we have to click on button in which we have define last data id and based on that id it will append next data on web page without refresh of whole page. Because here we have use Ajax with Laravel for implement Load More feature.




Ajax jQuery Load More Data in Laravel


Step 1 - Create Database


Following script will make table in your database.


USE `testing`;

/*Table structure for table `post` */

DROP TABLE IF EXISTS `post`;

CREATE TABLE `post` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;


Step 2 - Make Database Connection


Once you have create table, and you have insert some records in that table. Now we have move to start creating Load More feature in Laravel. First we want to make database connection. For this we have to go to config/database.php. In this file we have to define database configuration.


<?php

'connections' => [

        ....

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

        ..........

    ],

?>


After this we have to open .env file, and this file also we have to define Mysql Database connection configuration.


.......

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

........


Step 3 - Create Controller (LoadMoreController.php)


After making Mysql Database connection, Now we have to create Controller in Laravel. For this we have to go to command prompt, in which first we have to run "Composer" command, because it has manage Laravel framework dependency. We have to write following command for Create controller in Laravel.


php artisan make:controller LoadMoreController


It will make LoadMoreController.php file under app/Http/Controllers folder. In this controller we have use DB statement for database operation. In this controller we have make following method.

index() - This is root method of this LoadMoreController, which has been load load_more.blade.php file in browser.

load_data() - This method has received ajax request for fetch data from post table and convert into html format and send back to ajax request. In this method if id variable value greater than zero then it will fetch next five data, otherwise it has fetch first five data and convert into HTML and send to Ajax funciton, which has been display on web page.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LoadMoreController extends Controller
{
    function index()
    {
     return view('load_more');
    }

    function load_data(Request $request)
    {
     if($request->ajax())
     {
      if($request->id > 0)
      {
       $data = DB::table('post')
          ->where('id', '<', $request->id)
          ->orderBy('id', 'DESC')
          ->limit(5)
          ->get();
      }
      else
      {
       $data = DB::table('post')
          ->orderBy('id', 'DESC')
          ->limit(5)
          ->get();
      }
      $output = '';
      $last_id = '';
      
      if(!$data->isEmpty())
      {
       foreach($data as $row)
       {
        $output .= '
        <div class="row">
         <div class="col-md-12">
          <h3 class="text-info"><b>'.$row->post_title.'</b></h3>
          <p>'.$row->post_description.'</p>
          <br />
          <div class="col-md-6">
           <p><b>Publish Date - '.$row->date.'</b></p>
          </div>
          <div class="col-md-6" align="right">
           <p><b><i>By - '.$row->author.'</i></b></p>
          </div>
          <br />
          <hr />
         </div>         
        </div>
        ';
        $last_id = $row->id;
       }
       $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
       </div>
       ';
      }
      else
      {
       $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
       </div>
       ';
      }
      echo $output;
     }
    }
}

?>






Step 4 - Create View (load_more.blade.php)


In Laravel, it has use blade engine for process PHP file which has been store under resources/views/load_more.blade.php, it is has display output in browser. Under this file we have use ajax request, which send request to Controller for fetch data and display on web page without refresh of web page. For append data on web page, here we have use jquery append() method.


<!DOCTYPE html>
<html>
 <head>
  <title>Load More Data in Laravel using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Load More Data in Laravel using Ajax</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Post Data</h3>
    </div>
    <div class="panel-body">
     {{ csrf_field() }}
     <div id="post_data"></div>
    </div>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 var _token = $('input[name="_token"]').val();

 load_data('', _token);

 function load_data(id="", _token)
 {
  $.ajax({
   url:"{{ route('loadmore.load_data') }}",
   method:"POST",
   data:{id:id, _token:_token},
   success:function(data)
   {
    $('#load_more_button').remove();
    $('#post_data').append(data);
   }
  })
 }

 $(document).on('click', '#load_more_button', function(){
  var id = $(this).data('id');
  $('#load_more_button').html('<b>Loading...</b>');
  load_data(id, _token);
 });

});
</script>


Step 5 - Set Route


After this we have to set route of Controller method in Laravel framework. For this we have to open routes/web.php file.


Route::get('/loadmore', 'LoadMoreController@index');
Route::post('/loadmore/load_data', 'LoadMoreController@load_data')->name('loadmore.load_data');


Step 6 - Run Laravel Application


For run Laravel application, we have to go command prompt and write following commend, it will run Laravel application and display base url of Laravel application.


php artisan serve


It will return follwing url and for run this code you have to write following url.


http //127.0.0.1


This is complete step by step process with source code for make Load More data feature in Laravel by using Ajax jQuery with Mysql Database.