YouTube Icon

Code Playground.

How to Implement Dynamic Pagination using Laravel & AngularJS

CFG

How to Implement Dynamic Pagination using Laravel & AngularJS

Welcome! 

Today we will consolidate the Laravel system with Google's Angular JS. This has an assortment of employments, yet our article will tell you the best way to arrangement posts inside a blog. We will actualize dynamic pagination utilizing the inherent Laravel paginate alternative. 

At the hour of this post we couldn't discover existing documentation on this methodology. We are making this post with the expectation that you think that its accommodating. The whole code can be found on our GitHub. 

Instruments 

For this article we will utilize the accompanying apparatuses. It's significant that you are familar with the structures so as to utilize the framework to it's full focal points. 

  • AngularJS JS structure (we utilized 1.3.0) 
  • Laravel PHP structure (we utilized 4.2) 
  • Twitter Bootstrap - HTML/CSS structure 

How about we Get Started 

I'll accept that you as of now have a standard establishment of Laravel fully operational. On the off chance that you have to do that first, their site gives an extraordinary quickstart control. 

Make Routes and Views 

First we will make the courses and view expected to show your sites posts. We'll fabricate something straightforward utilizing the network styles gave by Bootstrap. You can redo this later once the framework is snared. In this model we'll incorporate 5 posts and next/back catches. 

Inside the courses document we will include a course for the JSON information and one for the real posts page. Add the accompanying to your application/routes.php record.

Route::get('posts', function() {  
    return Response::view('posts');
});

Route::get('posts-json', array(  
  'as' => 'posts-json', 
  'uses' => 'PostController@json' 
));

Create a new file called posts.blade.php in /app/views and place the following code in it. Note that we have included the Bootstrap library.

<!DOCTYPE html>  
<html lang="en">  
  <head>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
    <title>My Blog</title>
  </head>
  <body>  
    <div class="col-md-6 col-md-offset-3">  
      <h2>Posts</h2>

    </div> 
  </body>  
</html>  

Create Database Table & Controller

We will create a new model for our posts. We will name the new model Post. We will also create a new table to save all my posts with some basic structure. We will call this table posts and give it columns for:

  • ID (auto-increment)
  • Title (varchar, 100)
  • Content (varchar, 255)

You should utilize php craftsman migrate:make create_posts_table here however I won't really expound on that. Ideally your familar with the implicit movements. 

Since we have the posts table arrangement we will populate it with certain information. For testing I like to utilize the Faker library. On the off chance that you are new to how to utilize Faker I propose investigating our article on the most proficient method to seed a database with sham information in Laravel. 

Since we have the database table made and populated, lets make a controller for the posts. We will utilize this to paginate through the posts and get their information. We will make another document in the application/controllers envelope and call it PostController.php. Inside we will make another capacity json that will geneate the JSON information:

<?php  
class PostController extends BaseController {

    public function json(){  
        $posts = Post::paginate(5); // 5 is the number of items to show per page
        return Response::json($posts);
    }

}

Create "post" Model

We will now create a post model to connect our new controller to the post table. Create a new file called Post.php in the app/models directory. Inside the new file add the following code.

Add & Configure AngularJS

It is time to add AngularJS to the page and unlock all the potential that this framework can offer. Go ahead and include the library in your page. You will also need to create a JS file to place your code.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-resource.min.js"></script>  
<script src="js/app.js"></script>  

Important!

Laravel's blade templates use the same opening/closing brackets as AngularJS {{ }}. We must configure AngularJS to use [[ ]] instead to avoid conflicts. We can do that by adding the following code to our newly created js/app.js file.

var app = angular.module('CrowdforGeeks', ['ngResource'],  
 function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

Configure View File

Now that we have enabled AngularJS lets modify the HTML view to render it. Please note that we have now included ng-app in the body tag. This is critical.

<body ng-app="crowdforgeeks">  
    <div class="col-md-6 col-md-offset-3" ng-controller="postController" ng-init="getPosts()">  

      <h2>Posts</h2>

      <div class="list-group" >  
        <a href="#" class="list-group-item" ng-repeat="post in posts" >
          <h4 class="list-group-item-heading">[[ post.title ]]</h4>
          <p class="list-group-item-text">[[ post.content ]]</p>
        </a>
      </div>

      <div>
        <posts-pagination></posts-pagination>
      </div>

    </div>  
  </body>  

You will notice that we have used the directive in place of buttons. This will allow us to define the pagination based on the bootstrap styles inside our js/app.js file.

app.directive('postsPagination', function(){  
   return{
      restrict: 'E',
      template: '<ul class="pagination">'+
        '<li ng-show="currentPage != 1"><a href="javascript:void(0)" ng-click="getPosts(1)">&laquo;</a></li>'+
        '<li ng-show="currentPage != 1"><a href="javascript:void(0)" ng-click="getPosts(currentPage-1)">&lsaquo; Prev</a></li>'+
        '<li ng-repeat="i in range" ng-class="{active : currentPage == i}">'+
            '<a href="javascript:void(0)" ng-click="getPosts(i)">{{i}}</a>'+
        '</li>'+
        '<li ng-show="currentPage != totalPages"><a href="javascript:void(0)" ng-click="getPosts(currentPage+1)">Next &rsaquo;</a></li>'+
        '<li ng-show="currentPage != totalPages"><a href="javascript:void(0)" ng-click="getPosts(totalPages)">&raquo;</a></li>'+
      '</ul>'
   };
});

Fetch & Parse JSON Using AngularJS

If you remember in the beginning we created the route /posts-json/ to serve up the post information using JSON. Now its time to use it. When you load that page you should see something like this.

The data key in the JSON is the one that holds the content of all our posts. When we paginate with Laravel all we need to do is add a page parameter to the URL and Laravel will handle the rest. For example, /posts-json?page=2 would yield the second page of results.

Now its time to write the code snippet for AngularJS that will fetch and parse the JSON + enable the pagination functions. This requires that we write a new controller called postController in our app.js file.

Update! We've updated the code below to use pagination with ngResource. We'll leave the old code commented inline, in case you want to continue using that!

app.factory( 'Post', function($resource){  
  return $resource('post');
});

app.controller('postController', [ '$http', '$scope', function($http, $scope){

  $scope.posts = [];
  $scope.totalPages = 0;
  $scope.currentPage = 1;
  $scope.range = [];

  $scope.getPosts = function(pageNumber){

    if(pageNumber===undefined){
      pageNumber = '1';
    }
    Post.get({page: pageNumber},function(response){
    // Old pagination style using http
    // $http.get('/posts-json?page='+pageNumber).success(function(response) { 

      $scope.posts        = response.data;
      $scope.totalPages   = response.last_page;
      $scope.currentPage  = response.current_page;

      // Pagination Range
      var pages = [];

      for(var i=1;i<=response.last_page;i++) {          
        pages.push(i);
      }

      $scope.range = pages; 

    });

  };

}]);

Once you've added this code you should see the final result by visiting the /posts you created in the beginning.

Summary

We hope this article was helpful to you. If you have any comments please leave them below - thanks!




CFG