laravel yarja datatable style pagination code example
Example 1: laravel pagination ajax example
<!DOCTYPE html>
<html>
<head>
<title>Laravel Pagination 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>
<style type="text/css">
.box{
width:600px;
margin:0 auto;
}
</style>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Laravel Pagination using Ajax</h3><br />
<div id="table_data">
@include('pagination_data')
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.pagination a', function(event){
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
fetch_data(page);
});
function fetch_data(page)
{
$.ajax({
url:"/pagination/fetch_data?page="+page,
success:function(data)
{
$('#table_data').html(data);
}
});
}
});
</script>
Example 2: ajax jquery datatable display records with pagination in laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employees;
class EmployeesController extends Controller{
public function index(){
return view('employees.index');
}
public function getEmployees(Request $request){
$draw = $request->get('draw');
$start = $request->get("start");
$rowperpage = $request->get("length");
$columnIndex_arr = $request->get('order');
$columnName_arr = $request->get('columns');
$order_arr = $request->get('order');
$search_arr = $request->get('search');
$columnIndex = $columnIndex_arr[0]['column'];
$columnName = $columnName_arr[$columnIndex]['data'];
$columnSortOrder = $order_arr[0]['dir'];
$searchValue = $search_arr['value'];
$totalRecords = Employees::select('count(*) as allcount')->count();
$totalRecordswithFilter = Employees::select('count(*) as allcount')->where('name', 'like', '%' .$searchValue . '%')->count();
$records = Employees::orderBy($columnName,$columnSortOrder)
->where('employees.name', 'like', '%' .$searchValue . '%')
->select('employees.*')
->skip($start)
->take($rowperpage)
->get();
$data_arr = array();
foreach($records as $record){
$id = $record->id;
$username = $record->username;
$name = $record->name;
$email = $record->email;
$data_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email
);
}
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordswithFilter,
"aaData" => $data_arr
);
echo json_encode($response);
exit;
}
}