Load More Data on Page Scroll in Laravel


I think we are all familiar with load more technique in Facebook, Youtube etc. Today I will show you how to dynamically load the data on a button click instead of displaying the pagination links. Load more technique makes your website more interactive because the data is loaded without refreshing the page. In this tutorial, we use technologies like Ajax, Jquery, Bootstrap etc to create a beautiful load more data technique in the easiest way. 

SO LET'S START CODING

1) Create Table and Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   
}

 

2) Add Routes

 Route::get('demos/loaddata','DemoController@loadData');  
 Route::post('demos/loaddata','DemoController@loadDataAjax' );

 

3) Create DemoController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;

use Helper;

class DemoController extends Controller
{
    
    public function loadData()
    {
        $posts = Post::orderBy('created_at','DESC')->limit(2)->get();
        
        return view('demos.loaddata')->withPosts($posts);
    }
    
    public function loadDataAjax(Request $request)
    {
        $output = '';
        $id = $request->id;
        
        $posts = Post::where('id','<',$id)->orderBy('created_at','DESC')->limit(2)->get();
        
        if(!$posts->isEmpty())
        {
            foreach($posts as $post)
            {
                $url = url('blog/'.$post->slug);
                $body = substr(strip_tags($post->body),0,500);
                $body .= strlen(strip_tags($post->body))>500?"...":"";
                                
                $output .= '<div class="mdl-grid mdl-cell mdl-cell--12-col  mdl-shadow--4dp">
                                <div class="post">
                                    <a href="'.$url.'" class="nounderline" ><h2 class="post-title" >'.$post->title.'</h2></a>
                                    <div class="row">
                                       <div class="col-md-6">
                                           <h5 class="post-date" >Published:'.date('M j, Y', strtotime($post->created_at)).'</h5> 
                                       </div>
                                   </div>
                                    <div class="row">
                                        <div class="col-md-4 post-img">
                                            <img  class="img-responsive1"  src="'.Helper::catch_first_image($post->body).'" alt="'.$post->title.'" > 
                                        </div>
                                        <div class="col-md-8">
                                            <p class="text-justify">'.$body.'</p>
                                        </div>
                                    </div>
                                </div>   
                            </div>';
            }
            
            $output .= '<div id="remove-row">
                            <button id="btn-more" data-id="'.$post->id.'" class="nounderline btn-block mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" > Load More </button>
                        </div>';
            
            echo $output;
        }
    }
}

 

The Helper is a custom helper file created by me to load image thumbnail of each post. If you like to learn more about how to create custom helper function in laravel visit following link.

4) Create  View Page

The javascript code for in the view page

<script>
$(document).ready(function(){
   $(document).on('click','#btn-more',function(){
       var id = $(this).data('id');
       $("#btn-more").html("Loading....");
       $.ajax({
           url : '{{ url("demos/loaddata") }}',
           method : "POST",
           data : {id:id, _token:"{{csrf_token()}}"},
           dataType : "text",
           success : function (data)
           {
              if(data != '') 
              {
                  $('#remove-row').remove();
                  $('#load-data').append(data);
              }
              else
              {
                  $('#btn-more').html("No Data");
              }
           }
       });
   });  
}); 
</script>

Since we are using post ajax request in laravel we need to also pass csrf tokens along with the code since laravel always look for csrf tokens in the post and put requests. If we don't pass it we will get a 500 error. The reason why i used $(document).on('click',id,function(){}); instead of simple button click function is if we use button click function the button click will trigger only the first time. The reason that the handler is only being fired once is because the ".click" handler only applies to elements that are currently attached to the DOM. If you replace the HTML after making the AJAX call, the event handlers will be lost. So you should use an on method instead.

The Complete View Page

@extends('main')

@section('title',"Load More Data Demo -")

@section('meta','ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation')

@section('content')
 
<div class="row">
    <div class="col-md-10 col-md-offset-1">
        <h3 class="title-color text-center"><u>Load More Data Demo</u></h3>
    </div>
   
</div>

    <div class="row">
        <div class="col-md-10 col-md-offset-1 " id="load-data" >
            @foreach($posts as $post)
            <div class="mdl-grid mdl-cell mdl-cell--12-col  mdl-shadow--4dp">
            <div class="post">
                <a href="{{ url('blog/'.$post->slug) }}"  class="nounderline" ><h2 class="post-title" >{{ $post->title }}</h2></a>
                <div class="row">
                   <div class="col-md-6">
                       <h5 class="post-date" >Published: {{ date('M j, Y', strtotime($post->created_at)) }}</h5> 
                   </div>
               </div>
                <div class="row">
                    <div class="col-md-4 post-img">
                        <img  class="img-responsive1"  src="{{ Helper::catch_first_image($post->body) }}" alt="{{ $post->title }}" > 
                    </div>
                    <div class="col-md-8">
                        <p class="text-justify">{{  substr(strip_tags($post->body,'<pre>,<code>'),0,500) }}{{ strlen(strip_tags($post->body))>500?"...":"" }}</p>
                    </div>
                </div>
            </div>   
               
            </div>
            @endforeach
            
            <div id="remove-row">
                <button id="btn-more" data-id="{{ $post->id }}" class="nounderline btn-block mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" > Load More </button>
            </div>
            
            
        </div>
        
        
    </div>    


@stop

@section('scripts')

<script>
--------- Refer above javascript code  --------
</script>

@stop

As you can see the remove-row div is removed and replaced with server-side contents on ajax call. The sample image of above code is given below.

Load More Data Demo - Shareurcodes

The Demo

You can demo the following application by visiting the following link.

https://shareurcodes.com/demos/loaddata

If you have any suggestions or doubts please comment below and I try will respond to every one of you as early as possible.

 


Web development
21st Jul 2018 01:17:42 PM
PHP Laravel Javascript jQuery Ajax
30649

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.