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

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'
},
]
});

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 - how to show data with foreach in yajra datatable?

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',

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'));
}

Query String Filtering with Datatables in Laravel 5.4

im using YajraBox for Datatables, it is Laravel extension.
I want to make it work with my Query String Filtering, so idea is tah i need to pass search request to ajax request
This is part of my form imput:
http://127.0.0.1:8000/lots?make%5B%5D=TOYOTA
So result have to be: only lots made by TOYOTA
This is my script for datatables with YajraBox:
<script type="text/javascript">
$(document).ready(function(){
$('#table').DataTable({
bInfo: false,
searching: false,
processing: true,
serverSide: true,
ajax: '{{ url("/data") }}',
columns: [
{ data: 'date', name: 'date' },
{ data: 'bid', name: 'bid' },
{ data: 'auction_name', name: 'auction_name' },
{ data: 'pics_urls', name: 'pics_urls' },
{ data: 'company', name: 'company' },
{ data: 'model_name_en', name: 'model_name_en' },
{ data: 'model_type_en', name: 'model_type_en' },
{ data: 'grade_en', name: 'grade_en' },
{ data: 'mileage_en', name: 'mileage_en' },
{ data: 'model_year_en', name: 'model_year_en' },
{ data: 'color_en', name: 'color_en' },
{ data: 'displacement', name: 'displacement' },
{ data: 'transmission_en', name: 'transmission_en' },
{ data: 'scores_en', name: 'scores_en' },
{ data: 'start_price_en', name: 'start_price_en' },
{ data: 'result_en', name: 'result_en' }
]
});
});
</script>
This is my controllers for view and for ajax:
public function index()
{
return view('lots.browse');
}
public function indexData(LotFilters $filters)
{
$lots = Lot::filter($filters);
return Datatables::eloquent($lots)->make(true);
}
So what i think, i need to pass some howe ?make%5B%5D=TOYOTA to ajax request ajax: '{{ url("/data") }}',, any one know how to do it?
You can do this like:
"{{ url('/data') }}" + "?make="+value // where value contains TOYOTA in it
and get this value in controller like:
Input::get('make');

how to create Loading remote data search in Laravel 5.2?

This website is Book Hotel, After a user search to see the city and hotel.
I want to use Loading remote data select2 in laravel 5.2.
Github examples: https://select2.github.io/examples.html#data-ajax
Model City:
protected $fillable = [
'name', 'state', 'country', 'status'
];
Model Hotel:
protected $fillable =[
'name', 'address', 'phone', 'status', ...
];
HTML:
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Script:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
How to write in Laravel controller after send data from ajax?
HTML:
<select id="hotel" name="hotel">
<option value="hotel1">Hotel1</option>
<option value="hotel2">Hotel2</option>
</select>
Jquery and Ajax:
$(document).on('click','#hotel',function(e)
{
e.preventDefault();
var name=$(this).val('hotel');
$.ajax({
type:"POST",
url: "{{url('/controller/search')}}",
data: {
"_token": "{{ csrf_token() }}"
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('ok');
}
}
});
});
Laravel Controller:
public function search(Request $request)
{
$hotel=Hotel::where(['name',$request->name])->first();
return Response::json(array('status'=>TRUE,'hotel'=>$hotel));
}

Categories