Use datatable in laravel 8
<?php
/* =====In Controller file===== */
use DataTables;
public function ajax_get_blogs(Request $request)
{
if ($request->ajax()) {
$data = Blog::select('*');
return Datatables::of($data)
->addIndexColumn()
->addColumn('featured_image', function($row){
if($row->featured_image == ''){ $featured_image = asset("upload/image-not-found.jpg"); } else { $featured_image = asset("upload/" . $row->featured_image); }
$featured_image_view = '<img src="'. $featured_image .'">';
return $featured_image_view;
})
->addColumn('action', function($row){
$btn = '<a href="javascript:void(0)" data-blog_id = ' . $row->id . ' class="edit btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action','featured_image'])
->make(true);
}
return view('admin.blogs.blogs-list');
}
/* =====In Blade file===== */
?>
<html>
<head>
<style>
img {
border: 1px solid red;
width: 200px;
height: 150px;
object-fit: cover;
}
img[src=""] {
background:url("http://localhost/laravel-testing/upload/images/blogs/build.jpg");
object-fit: cover;
}
</style>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<table id="blog_post_table">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Description</th>
<th>Image</th>
<th width="100px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.css">
<script>
jQuery(document).ready(function($){
$(function () {
var table = $('#blog_post_table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('blogs.AjaxGetBlogs') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'title', name: 'title'},
{data: 'description', name: 'description'},
{data: 'featured_image', name: 'featured_image', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
});
</script>
</body>
</html>
Comments
Post a Comment