Laravel Load More Data on Page Scroll – Laravel 5

Laravel Load More Data on Page Scroll – Laravel 5

In this post exercise, we will disclose to you how to Laravel Load More Data from database utilizing jQuery and PHP Laravel.

Laravel Load More Data:: we are all comfortable and familiar with load more method in Facebook, Youtube and so on. Today we will demonstrate to you generally accepted methods to progressively stack the information on a catch click as opposed to showing the pagination joins. Stack more procedure makes your site more intelligent in light of the fact that the information is stacked without invigorating the page. In this post exercise, we utilize innovations like Ajax, Jquery, Bootstrap and so forth to make a lovely load more information method in the most straightforward way.

we don’t have need to click anyplace to load information since information is stacking on page scroll consequently from MySQl database.

There are such a variety of site that utilization a similar rationale to load information on page look over, this is extremely helpful with a few cases.

It will check if information length is equivalent to 0 then show message for “No more records!” and if information length is more than 0 then it add html information to list.

Here is a straightforward stride to tell you about stacking information naturally on page look through and through utilizing jQuery and PHP.

SO LET’S START CODING for Laravel Load More Data on Page Scroll

1) Create Table and Model for Laravel Load More Data on Page Scroll


namespace App;

use Illuminate\Database\Eloquent\Model;
// Create Post Model
class Post extends Model
{

}

2) Add Routes for Laravel Load More Data on Page Scroll

// add Route for Laravel Load More Data
// routes/web.php Laravel 5.3 or 5.4
// app/Http/web.php Laravel 5 to 5.2

Route::get('demos/loaddata','LoadController@loadData');
Route::post('demos/loaddata','LoadController@DataAjaxload' );

3) Create LoadController for Laravel Load More Data on Page Scroll

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;

use Helper;
// LoadController Controller for Laravel Load More Data
class LoadController extends Controller
{
    // Dataload function
    public function Dataload()
    {
		// get post data in DESC order
        $post_data = Post::orderBy('created_at','DESC')->limit(2)->get();
        // return DESC order data
        return view('demos.loaddata')->withPosts($post_data);
    }
    
	// function DataAjaxload
    public function DataAjaxload(Request $request)
    {
        $set_output = '';
        $id = $request->id;
        
        $post_data = Post::where('id','<',$id)->orderBy('created_at','DESC')->limit(2)->get();
        
        if(!$post_data->isEmpty())
        {
            foreach($post_data as $post_val)
            {
                $set_url = url('blog/'.$post_val->slug);
                $body_data = substr(strip_tags($post_val->body),0,500);
                $body_data .= strlen(strip_tags($post_val->body))>500?"...":"";
                                
                $set_output .= '<div class="mdl-grid grids mdl-cell mdl-shadow--4dp col-md-12  ">
                                <div class="post grids">
                                    <a href="'.$set_url.'" class="nounderline grids" ><h2 class="grids post-title" >'.$post_val->title.'</h2></a>
                                    <div class="row grids">
                                       <div class="col-md-6 grids">
                                           <h5 class="post-date grids" >Published:'.date('M j, Y', strtotime($post_val->created_at)).'</h5> 
                                       </div>
                                   </div>
                                    <div class="row">
                                        <div class="col-md-4 post-img1 grids">
                                            <img  class="img-responve1 grids"  src="'.Helper::catch_first_image($post_val->body).'" alt="'.$post_val->title.'" > 
                                        </div>
                                        <div class="col-md-8 grids">
                                            <p class="text-justify">'.$body_data.'</p>
                                        </div>
                                    </div>
                                </div>   
                            </div>';
            }
            
            $set_output .= '<div id="remove-row grids">
                            <button id="btn-more " data-id="'.$post_val->id.'" class="nounderline grids btn-block mdl-button mdl-js-button" > Load More </button>
                        </div>';
            
            echo $set_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 for Laravel Load More Data on Page Scroll

The javascript code for in the view page

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

Since we are using post ajax request in laravel we need to in like manner pass csrf tokens nearby the code since laravel reliably scan for csrf tokens in the post and put requests. In case we don’t pass it we will get a 500 goof. The inspiration driving why i used $(document).on('click',id,function(){}); instead of essential catch click limit is whether we use get click work the catch snap will trigger only the principal gone through. The reason that the handler is simply being ended once is because of the “.snap” handler just applies to parts that are at this moment affixed to the DOM. If you supplant the HTML ensuing to making the AJAX call, the event handlers will be lost. So you should use an on strategy.

The Complete View Page for Laravel Load More Data

@extends('main')
@section('title',"Load More Data Example - onlinecode")
@section('meta','In this post exercise, we will disclose to you how to Laravel Load More Data from database utilizing jQuery and PHP Laravel.')

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


@stop

@section('scripts')

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

Leave a Comment

Your email address will not be published. Required fields are marked *

87  +    =  88

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US