Laravel - how to show data with foreach in yajra datatable? - php

I want to show audit trail data in datatables. column old_values and new_values are array in database. i'm using yajra-datatable.
Old_values/new_values value in db something like this
{"updated_at":"2021-05-03 09:30:17.248","var_allowance_1":"500.00",**"var_allowance_2":"300.00"**}
But in the view, column old/new_values, it only show the latest array. for example only show var_allowance_2 = 300.00 instead of all value (i.e)
updated_at = 2021-05-03 09:30:17
var_allowance_1= 500.00
var_allowance_2=300.00
here is the script in blade
<script>
$(document).ready(function(){
$('#user_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{url('/')}}/report/data",
type: "GET",
'data': function ( d ) {
d._token = "{{ csrf_token() }}";
d.date1 = $('#date1').val();
d.date2= $('#date2').val();
}
},
columns: [
{
data: 'DT_RowIndex',
name: 'DT_RowIndex'
},
{
data: 'auditable_type',
name: 'auditable_type'
},
{
data: 'event',
name: 'event'
},
{
data: 'user_id',
name: 'user_id'
},
{
data: 'created_at',
name: 'created_at'
},
{
data: 'old_values',
name: 'old_values'
},
{
data: 'new_values',
name: 'new_values'
},
]
});
});
</script>
here is the controller
public function audits_data(Request $request)
{
$user = Auth::user();
$date1 = $request->input('date1');
$date2 = $request->input('date2');
$user = Auth::user();
$data = \OwenIt\Auditing\Models\Audit::select(['id', 'event', 'created_at', 'auditable_type','user_id','old_values','new_values'])->orderBy('updated_at', 'DESC')->whereDate('created_at','>=',$date1)->whereDate('created_at','<=',$date2)->get();
return DataTables::of($data)
->addIndexColumn()
->addColumn('old_values', function ($data) {
if (is_array($data->old_values) || is_object($data->old_values))
{
$old = [];
foreach($data->old_values as $attribute => $value)
{
"<b>$attribute = </b>$value<br>";
}
}
return $old;
})
->addColumn('new_values', function ($data) {
if (is_array($data->new_values) || is_object($data->new_values))
{
$new = [];
foreach($data->new_values as $attribute => $value)
{
$new= "<b>$attribute = </b>$value<br>";
}
return $new;
}
})
->rawColumns(['old_values','new_values'])
->make(true);
}
If i am not using server side on blade, with using below code on blade, it works.
How do I implement it on a server-side datatable?
<td>
#if (is_array($audit->old_values) || is_object($audit->old_values))
#foreach($audit->old_values as $attribute => $value)
<b>{{ $attribute }} =</b> {{ $value }}<br>
#endforeach
#endif
</td>

In laravel -> controller calling function you can return data table object like this
I have added extra buttons for action to return in the table for the custom column
public function getProducts()
{
$products = ProductModel::all();
return Datatables::of($products)->addColumn('action', function ($products) {
//create links for edit and delete functionality
return '<i class="material-icons col-blue">mode_edit</i>
<i class="material-icons col-red">delete</i>';
})
->addIndexColumn()
->make(true);
}
In blade template HTML Part
<div class="body">
<div class="table-responsive">
<table id="product-table" class="table table-bordered table-striped table-hover dataTable">
<thead>
<tr>
<th>#</th>
<!--th>Product ID</th-->
<th>Product Name</th>
<th>Product System</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
In Js part of the template
$(document).ready(function(){
//Exportable table
var productDT = $('#product-table').DataTable({
responsive : true,
dom : 'Blfrtip',
autoWidth : true,
paging : true,
pagingTypeSince : 'numbers',
pagingType : 'full_numbers',
processing : true,
serverSide : true,
ajax: '{!! route('product.data') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex' },
//{ data: 'product_id', name: 'product_id' },
{ data: 'product_name', name: 'product_name' },
{ data: 'product_system', name: 'product_system' },
{ data: 'is_active', name: 'is_active' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
//search textbox filter code
productDT.on( 'order.dt search.dt', function () {
productDT.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
});
}).draw();
});
up and running example from my live project
In your case
data: 'old_values', will be data: 'var_allowance_1',
data: 'new_values', will be data: 'var_allowance_2',

Related

How to pass parameter to controller using laravel data table?

I need to pass id to my controller function via laravel datatable i.e yajra datatable,
i need to recive id in my function to fetch data but its not posting at all.
I have tried many ways but no luck
below is my code,
jquery,
$(function() {
var id = "<?php echo $id;?>";
// alert(id);
var table = $('#data-table').DataTable({
processing: true,
serverSide: true,
searchable:true,
ajax: "{{ route('vendor.getOperationTimes') }}",
// type:"GET",
// data: {
// "_token": $('meta[name="csrf-token"').attr('content'),
// "id": id
// },
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex'
},
{
data: 'name',
name: 'name'
},
{
data: 'day',
name: 'day'
},
{
data: 'start_time',
name: 'start_time'
},
{
data: 'end_time',
name: 'end_time'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
controller function,
public function getOperationTimes(Request $request)
{
if ($request->ajax()) {
$station_id = $request['id'];
// echo $station_id;exit;
$station = new Station();
$getData = $station->getOperationTimes($station_id);
return Datatables::of($getData)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'Edit ';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
route,
Route::get('getOperationTimes',[VendorStationController::class, 'getOperationTimes'])->name('getOperationTimes');
please help me someone at the earliest
Route::get('getOperationTimes/{id}')
ajax: "{{ route('vendor.getOperationTimes', ['id' => id]) }}",
You can try above code.

Laravel - Datatable with post method show raw data instead of table

i have an audit trails report to show the data based on range of date, selected by user. So user will select the range in page (audits) and when click submit will redirect to page (audits_view).
I want to show the data in datatables, but in audits_view, the result that i get is only raw data like this
{"draw":0,"recordsTotal":490,"recordsFiltered":490,"data":[{"id":144586,"event":"created","created_at":"2021-05-19 10:28:50.660","auditable_type":"App\\Model\\Loglogin","user":null},{"id":144585,"event":"created","created_at":"2021-05-19
here is the audits_view blade and controller
<table id="user_table" class="table table-bordered data-table">
<thead>
<tr>
<th width="35%">auditable_type</th>
<th width="35%">event</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function(){
$('#user_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{url('/')}}/report/audits",
type: "POST",
dataType: "json",
'data': function ( d ) {
d._token = "{{ csrf_token() }}";
},
columns: [
{
data: 'auditable_type',
name: 'auditable_type'
},
{
data: 'event',
name: 'event'
},
]
});
});
</script>
here is the controller
public function audits_view(Request $request)
{
$this->authorize('view_audit_trails');
$user = Auth::user();
$date1= $request->input('date1');
$date2= $request->input('date2');
$data = \OwenIt\Auditing\Models\Audit::with('user')
->select(['id', 'event', 'created_at', 'auditable_type'])
->whereDate('created_at','>=',$date1)>whereDate('created_at','<=',$date2)->get();
return DataTables::of($data)
->make(true);
return view('report.audits_view', compact('date1','date2','user'));
Following is just basic idea:
The view function should be like this:
public function audits_view(Request $request) {
$this->authorize('view_audit_trails');
$user = Auth::user();
$date1= $request->input('date1');
$date2= $request->input('date2');
return view('report.audits_view', compact('date1','date2','user'));
}
and for data table you should create new post route and on that route the function should be like this:
public function audits_data(Request $request) {
$date1= $request->input('date1');
$date2= $request->input('date2');
$data = \OwenIt\Auditing\Models\Audit::with('user')
->select(['id', 'event', 'created_at', 'auditable_type'])
->whereDate('created_at','>=',$date1)>whereDate('created_at','<=',$date2);
return DataTables::of($data)
->make(true);
}
the js should be something like this:
$('#user_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{url('/')}}/report/audits",
type: "POST",
dataType: "json",
data: function ( d ) {
d._token = "{{ csrf_token() }}",
d.date1 = $('#date1').val(),
d.date2 = $('#date2').val(),
},
columns: [
{
data: 'auditable_type',
name: 'auditable_type'
},
{
data: 'event',
name: 'event'
},
]
});

Yajra Datatable relationship showing records in one column

Here's my ID column data structure
ID: [1,2,3,4,5,6,7,8]
Here is my controller's code.
$transaction = ExpenseEntry::with('transaction');
return DataTables::eloquent($transaction)
->editColumn('transaction', function (ExpenseEntry $expense) {
return $expense->transaction->map(function ($transaction) {
return $transaction->id;
});
})->make(true);
and Javascript Function
$(document).ready(function () {
$('#data-table').DataTable({
"ordering": false,
"processing": true,
"serverSide": true,
"ajax": '{!! route('
expense_dts ') !!}',
columns: [{
data: 'id',
name: 'id'
},
{
data: 'expense_type',
name: 'expense_type'
},
{
data: 'amount',
name: 'amount'
},
{
data: 'date',
name: 'date'
},
{
data: 'description',
name: 'description'
},
{
data: 'transaction',
name: 'transaction.id'
}
]
});
});
It is working but the problem is it is showing all the transacation.id in a table like this [1,2,3,4,5,6]
I want to get them like each id in each row with its column.

How to use two or more DataTables with using yajra(Laravel)

I have 'post' table in my database. In post table, I have 'LanguageID' column.
When I store/save data, It will make two records, first record with language id = 1 and the second record with language id = 2.
Now, I want to show all 'post' data separately.
Controller
public function index(Request $request)
{
$languages = Language::where('IsActive', 1)->get();
if($request->ajax()) {
foreach ($languages as $lang) {
$post = Post::where('LanguageID', $lang->id)->get();
}
return Datatables::of($post)
->addColumn('action', function($post){
return '<a id="edit" class="btn btn-info"
href="post/' . $post->id . '/edit">
<i class="glyphicon glyphicon-edit icon-white"></i>
Edit
</a>
<button type="button" class="btn btn-danger"
onclick="checkDelete('.$post->id.', this);"
data-token="{{ csrf_token() }}">
<i class="glyphicon glyphicon-trash icon-white"></i>
Delete
</button>';
})
->make(true);
}
return view('pages.back-end.lists.post')->with('languages', $languages);
}
This is my view
This is my yajra
$(function(){
$("#data-post").DataTable({
processing: true,
serverSide: true,
ajax:{
url: "{{ url("post") }}",
data:{ _token: "{{csrf_token()}}", languageid: languageid}
},
columns: [
{ data: 'PostDate', name: 'PostDate'},
{ data: 'PostTitle', name: 'PostTitle' },
{ data: 'PostSlug', name: 'PostTitle' },
{ data: 'action', name: 'action'}
]
});
});
You can use yajra datatables filter based upon language id reffer this - https://datatables.yajrabox.com/collection/custom-filter
or
use can do manual ajax call on button indonesia and english by passing language id and then destroy and reintiate datatable like that -
function customFilters(languageid)
{
$('#datatableid').dataTable().fnDestroy();
$('#datatableid').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
"url": url_link,
"dataType": "json",
"type": "POST",
"data":{ _token: "{{csrf_token()}}", languageid: languageid}
},
"columns": [
{ "data": "id" },
{ "data": "PostDate" },
{ "data": "PostTitle" },
{ "data": "PostSlug"},
{ "data": "LanguageID"},
{ "data": "actions" ,orderable: false, searchable: false}
]
});
}
Hope this will help you.
You have to parse the language ID with doing like this in you dataTable.php
public function language($id){
$this->language = $id;
return $this;
}
public function query(Post $model)
{
$query = Post::where('LanguageID',$this->language)->select('posts.*');
return $this->applyScopes($query);
}
then, call the dataTable manually
$('.tabPost').each(function(){
var lang_id = $(this).attr('id');
var oTable = $("#data-post" + lang_id).DataTable({
processing: true,
serverSide: true,
dom: 'Bfrtip',
order: [[0, 'desc']],
buttons: ['create',
'export',
'print',
'reset',
'reload',
'colvis',
],
ajax:{
url: "{{ url("post") }}",
data: function(d) {
d.LanguageID = lang_id
}
},
columns: [
{ data: 'id', name: 'id'},
{ data: 'PostDate', name: 'PostDate'},
{ data: 'PostTitle', name: 'PostTitle' },
{ data: 'PostSlug', name: 'PostTitle' },
{ data: 'action', name: 'action'}
]
});
$('#'+lang_id).on('click', function(e){
oTable.draw();
e.preventDefault();
});
});
and don't forget to set your controller like this
public function index(PostDataTable $dataTable, Request $request)
{
$languages = Language::where('IsActive', 1)->get();
return $dataTable->language($request->input('LanguageID'))->render('pages.back-end.lists.post', compact('languages'));
}

how to display ajax server response data into datatable using php

after initialize data-table in my page its working fine, but i need to display server response data dynamically in data-table. I can receive data in console.log(data)
$(document).ready(function () {
$.ajax({
url: 'xxxxxx/xxxxxxx',
method: 'POST',
success: function (data) {
$('#datatable').dataTable({
data: data,
serverside:true,
columns: [
{ 'data': 'UserId' },
{ 'data': 'UserDepartment' },
{ 'data': 'UserCourse' },
{ 'data': 'UserName' },
{ 'data': 'UserBirthDate' },
{ 'data': 'UserEmail' },
{ 'data': 'UserContact' }
]
});
}
});
});
Try This:
<?php
$sql = "SELECT FROM user";
$sql_result = $conn->query($sql);
$response = array('data' => $sql_result );
echo json_encode($response);
?>
$(document).ready(function() {
$.ajax({
url: 'xxxxxx/xxxxxxx',
method: 'POST',
dataType: 'json',
success: function(data) {
$('#datatable').dataTable({
data: data,
serverside: true,
columns: [{
'data': 'UserId'
}, {
'data': 'UserDepartment'
}, {
'data': 'UserCourse'
}, {
'data': 'UserName'
}, {
'data': 'UserBirthDate'
}, {
'data': 'UserEmail'
}, {
'data': 'UserContact'
}]
});
}
});
});
I think you have things out of order you could try this:
$(document).ready(function ()
{
// Setup - add a text input to each footer cell
$('#DataTable tfoot th').each(function ()
{
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
var table = $('#DataTable').DataTable({
"select": true,
"processing": true,
"serverSide": true,
"ajax": {
"url": "./ServerSide.php",
"type": "POST"
}
});
});
I'm pretty sure you don't even have to list the column names, they'll be picked up in your file passed to the url.
HTML CODE
<table class="table table-bordered" id="datatables">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
jQuery(document).ready(function(){
$('#datatables').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
"url": "fetch.php",
"dataType": "json",
"type": "POST"
},
"columns": [
{ "data": "id"},
{ "data": "name"},
{ "data": "email"},
{ "data": "mobile"},
{ "data": "manage"}
],
"columnDefs": [ {
"targets": [0,4],
"orderable": false
} ],
"order": [[ 1, "ASC"]],
});
$(document).ready(function() {
$('#dataTables').DataTable();
} );
});
</script>
PHP CODE
$link = mysqli_connect("localhost","root","","dbName")
$req = mysqli_query($link,"SELECT * FROM register where delete_status = 0");
$s = (isset($_POST['search']['value'])) ? $_POST['search']['value'] : '';
if(!empty($s))
{
$req = mysqli_query($link,"SELECT * FROM register WHERE name LIKE '%$s%' ");
}
$totalData = mysqli_num_rows($req);
$totalFiltered = mysqli_num_fields($req);
$data = array();
if(!empty($req))
{
foreach ($req as $key=>$value)
{
$edit = "";
$delete = "";
$nestedData['id'] = $key+1;
$nestedData['name'] = $value['name'];
$nestedData['email'] = $value['email'];
$nestedData['mobile'] = $value['mobile'];
$nestedData['manage'] = "<a href='$edit' class='btn btn-warning btn-xs'><i class='fa fa-pencil'></i> Edit</a> <a onclick='return delet()' href='$delete' class='btn btn-danger btn-xs confirm-delete' ><i class='fa fa-trash'></i> Delete</a>";
$data[] = $nestedData;
}
}
$json_data = array(
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered),
"data" => $data
);
echo json_encode($json_data);
include jquery file
jquery.min.js
bootstrap.min.js
jquery.dataTables.min.js
dataTables.buttons.min.js
dataTables.bootstrap.min.js

Categories