Laravel Pagination Ajax

  • Posted by Sharad Jaiswal

    Creating Ajax based pagination is Laravel 5.6

    Ajax: Ajax (Asynchronous JavaScript and XML) is a technique to update a specific part of webpage asynchronously without reloading the page.In this article, we are going to see how to use ajax to create pagination in Laravel.

    Prerequisites.

    I am assuming that you have already installed and configured Laravel 5.6 on your server. If not here is a good tutorial for installing and creating CRUD in Laravel.

    Step to create Laravel Pagination Ajax

    Step1: Configuring our Routes
    Step2: Creating our Controller Actions to handle Requests
    Step3: Creating our Model
    Step4: Creating our Views
    Step5: Writing Javascript function to Fetch records using Ajax in Laravel

    Configuring our Routes

    In add following code in routes/web.php file

    Route::get('/paginate', ['uses'=>'PostController@index']);
    
    Check Out Latest Laravel Interview Questions 2018

    Creating our Controller

    Create a new file and add the following code to it.

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Post;
    use App\Http\Controllers\Controller;
    
    class PostController extends Controller
    {
    /**
    * Show all of the users for the application.
    *
    * @return Response
    */
    public function index()
    {
    $posts= Post::paginate(10);
    // handling ajax requests
    if ($request->ajax()) {
                return view('post.ajaxResults', compact('posts'));
     }
    
    return view('post.index', ['posts' => $posts]);
    }
    }
    

    Creating Our Model

    Create a new file named post.php in your app folder and add following code to it.

    //app/post.php

    <?php namespace App; 
    use Illuminate\Database\Eloquent\Model;
    class Post extends Model { 
    public $fillable = ['title','description']; 
    } 
    

    Creating our Views

    In resources/views/posts directory creating following files

    • index.blade.php
    • ajaxResults.blade.php

    In resources/views/posts/index.blade.php put follwing code and save it.

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="UTF-8">
        <title>Ajax Pagination in Laravel</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.0.0/cerulean/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <div class="row">
                
                <div class="col-sm-9">
                    @if ($posts)
                        <section class="data">
                            @include('ajaxResults')
                        </section>
                    @endif
                </div>
    
                <div class="col-sm-3">
                </div>
            </div>
        </div>
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.min.js"></script> 
    @include('ajaxscripts')
    </body> 
    </html>

    In resources/views/posts/ajaxResults.blade.php put follwing code and save it.

     <table class="table table-bordered"> 
     <tr>
     <th>Post Title</th>
     <th>Description</th> 
     </tr>
     @foreach ($posts as $post)
     <tr>
     <td>{{ $post->title }}</td>
     <td>{{ $post->description }}</td>
     </tr>
     @endforeach
     </table>
     {!! $post->render() !!}
    Read Best Ajax Interview Questions for Interview

    Writing Javascript functions

    Creating a new file in resources/views/ named ajaxscripts.blade.php and following code in it.

    <script type="text/javascript">
    
    $(function() {
        $('body').on('click', '.pagination a', function(e) {
            e.preventDefault();
    
            $('.data li').removeClass('active');
            $(this).parent('li').addClass('active');
            var page_no=$(this).attr('href').split('page=')[1]; 
            getPosts(page_no);
            
        });
    
        function getPosts(page) {
           var uri={{url('paginate')}};
            $.ajax({
                url :uri+'?page=' + page,  
            }).done(function (data) {
                $('.data').html(data);  
            }).fail(function () {
                alert('Error in Loading Posts.');
            });
        }
    });
    
    </script>
    

Please Login or Register to leave a response.

Related Articles

Laravel Tutorials

Laravel 5.5 Middleware complete Tutorial

In Laravel, you can think middleware as a system or tool that are used to filter all HTTP requests entering your application. Middleware works between request and response of our application. It sits ..

Laravel Tutorials

Laravel Pagination

According to Wikipedia Pagination is a process of separating or dividing a document or digital contents into discrete pages. In Core PHP and other frameworks, paginating record is a painful task. Lara..

Laravel Tutorials

Configuring Errors & Logging in Laravel 5

Laravel comes with excellent error and exception handling feature. When you install Laravel framework (MVC) error and exception handling is configured at the same time. In this tutorial, we will see h..