Laravel and DataTables.net - laravel

I am beginner in Laravel.
I use in my project Laravel 7. I use yajra/laravel-datatables in my project.
I have this code:
<table class="table table-bordered data-table ">
<thead>
<tr>
<th>ID</th>
<th>Tytuł</th>
<th>Status</th>
<th width="100px">Akcja</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('tabelka.tabelka2') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
// {data: 'id', name: 'id'},
{data: 'title', name: 'title'},
{data: 'enable', name: 'enable'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
and controller:
public function tabelka2(Request $request)
{
// return Datatables::of(Page::query())->make(true);
if ($request->ajax()) {
$data = Page::get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
//$btn .= 'View';
$btn = ' ';
$btn .= ' ';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
}
It's work fine.
How do I search for columns other than title, enable? I need to search for description and keywords.
If enable = 1 - I would like to display "active". Otherwise "inactive"
I would like to "pack" the title value in: ...])}} "> description
Anyone know how to do this? Please help

1 - Im not sure if i understand and i dont have reputation enought to comment. Where does the description comes from? But if you want manipulate the input string or compare with value that are on database i suggest you begin here and here
2 - You can use editColumn function and check $row value. Something like this:
->addIndexColumn()
->editColumn('columnName', function ($row){
if($row->atributte == 1)
return 'true';
else return 'false';
}
3 - Again im not sure if i understand. If you want concaten or manipulate two values that are in database you can use de last tip.
You can see more at Docs

Related

My laravel Yajra datatable does not render. It says invalid json response. However I can not read the error since the response is empty

Hello I have the following controller method to return data to my datatable in Laravel,
Controller Method
public function get(Request $request) {
return Datatables::of(AppUser::all())
->addColumn('status', function ($user) {
if ($user->status == 1) {
return '<span class="label label-success">Active</span>';
} else {
return '<span class="label label-danger">Inactive</span>';
}
})
->addColumn('actions', function ($user) {
return view('backend.appuser.actionButton', compact('user'))->render();
})
->make(true);
}
Then in the view I render the datatable, I have the following code.
<table id="users-table" class="table table-condensed table-hover">
<thead>
<tr>
<th>Username</th>
<th>NIC</th>
<th>Mobile</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
Inside my script tag I have the below code
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route("admin.app-access.user.get") }}',
type: 'get',
data: {status: 1, trashed: false}
},
columns: [
{data: 'email', name: 'email'},
{data: 'nic', name: 'nic'},
{data: 'mobile', name: 'mobile'},
{data: 'status', name: 'status'},
{data: 'actions', name: 'actions'}
],
pageLength:25,
lengthMenu:[[10,25,50,100,-1],[10,25,50,100,"All"]],
order: [ [ 0, "desc" ] ],
dom: "lBfrtip",
buttons:
[
{extend: 'excel', footer: true, title: 'User Details'},
{extend: 'pdf', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'},
{extend: 'print', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'}
],
searchDelay: 500
});
});
The Error
When I go to the index page that the datatable is loaded, it says,
DataTables warning: table id=users-table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
What I tried
I tried making a little syntax error in the above controller method to see if the application crashes. If the application crashes, it means that the request sent from the datatable must have hit my controller method. (App actually crashed, so the request from the datatable is coming to my controller method.)
I went to the network tab in my developer tools and inspected the response for the request sent from the data-table. The response is empty. It just shows three empty lines. Since the response is empty, I can not figure out what the error is.
Below picture shows the response I got.
(I am using Laravel 5.4)
I have added rawColumns before the ->make(true) will you try with this solution once?
It should work I guess so!
So here your will looks like...
public function get(Request $request) {
return Datatables::of(AppUser::all())
->addColumn('status', function ($user) {
if ($user->status == 1) {
return '<span class="label label-success">Active</span>';
} else {
return '<span class="label label-danger">Inactive</span>';
}
})
->addColumn('actions', function ($user) {
return view('backend.appuser.actionButton', compact('user'))->render();
})
->rawColumns(['status', 'actions'])
->make(true);
}

A non well formed numeric value encountered when creating a custom Yajra Datatable

I am using Laravel and I want to create a custom server side Yajra Datatable.
My Ajax call is below:
let table = $('#myTable').DataTable({
"bLengthChange": false,
"iDisplayLength": 20,
"info": false,
processing: true,
serverSide: true,
ajax: {
url: "/myURL",
dataSrc: '',
data: function (d) {
d.start = '2020-04-01';
d.end = '2020-07-20';
d.table = true;
},
},
columns: [
{data: 'name', name: 'name'},
{data: 'nameMerged', name: 'nameMerged'},
{data: 'count', name: 'count'},
],
});
$("#myTable").append('<tfoot><tr><th>' + 'Total:' + '</th><th></th><th>'
+ total + '</th></tr></tfoot>');
The controller for the ajax call is getting an array from another function that looks like (tableObject) and transforms the array into a Datatable.
DataTable transform function:
public function transformTable($start, $end)
{
$tableObject = $this->getTableData($start, $end);
return DataTables::of($tableObject['datasets'])
->addIndexColumn()
->addColumn('name', function ($row) {
return $row->name;
})
->addColumn('nameMerged', function ($row) {
return $row->nameMerged;
})
->addColumn('count', function ($row) {
return $row->count;
})
->setRowClass(function ($data) {
return 'tr-basic';
})
->with('total', $tableObject['total'])
->make(true);
}
Table in Blade file:
<div>
<h2>Employees:</h2>
<table id="myTable" class="bravo-list">
<thead>
<tr>
<th class="th-toggler"></th>
<th class="th-fullname" id="th-employee">Mitarbeiter</th>
<th class="th-fullname" id="th-count"># Bravos</th>
</tr>
</thead>
</table>
</div>
This, however, returns the following error:
A non well formed numeric value encountered
The error occurs beacause the variables "start" and "end" in the ajax call are reserved keywords. I changed the name of the variables and it works now as aspected.

Yarja Datatables - getting results for specific id

I am trying to have the ability for the user to click on a link and get jobs for a specific operative. As a test I am only using three field from a job table
id,operative_id,address
The operative ID is the parameter I wish to pass to the datatable ajax controller.
The operative ID is sent by the jobs controller to a blade template in the normal manner. I then have a table area:
<table class="table data-table" id="thetable">
<thead>
<th>id</th>
<th>address</th>
<th>operative id</th>
<th></th>
</thead>
<tbody>
</tbody>
</table>
In the javascript area of the blade template I have
<script type="text/javascript">
$(function () {
var table = $('.data-table').DataTable({
"iDisplayLength": 25,
"lengthMenu": [ [10, 25, 50,100,200, -1], [10, 25, 50,100,200, "All"] ],
columnDefs: [
{
targets: -1,
className: 'dt-right'
}],
processing: true,
serverSide: true,
ajax:"{{route('testData',['id' => $id])}}",
columns: [
{ data: 'jobID', name: 'jobID' , orderable: false, searchable: false},
{data: 'address', name: 'address'},
{data: 'operative_id', name: 'operative' },
{data: 'action', name: 'action', orderable: false, searchable: false},
],
});
});
</script>
In my controller I have this function:
public function testData (Request $request, $id)
{
$jb = DB::table('job')
->select('id AS jobID','operative_id','address')->where('operative_id',$id)->get();
return Datatables::of($jb)
->addColumn('action', function($pubs){
$btn = '<div style="float:right">
<i class="fas fa-book" ></i><i class="fas fa-edit" ></i></div>';
return $btn;
})
->make(true);
}
The controller (DatatablesController) has other functions that work perfectly and are much more complex, but I only want to show the jobs of the $id passed in. The error I am getting is a 500 error
Class App\Http\Controllers\DataTablesController does not exist
which of course it does.
For example this works perfectly:
public function allJobs(Request $request)
{
$user = Auth::user();
$cl = $user->client_id;
$jb = DB::table('job')
->join('job_status', 'job.jobStatus_id', '=', 'job_status.id')
->join('customers', 'job.customer_id', '=', 'customers.id')
->join('users', 'job.operative_id', 'users.id')
->where('job.client_id', $cl)
->select(['job.id as id', 'job_status.status as status', 'job.customer_id as customer_id', 'customers.customer as customer', 'users.name as operative','job.address as address','job.postcode as postcode','job.slug as slug','job_status.id as jobStatusID'])
->get();
return Datatables::of($jb)
->addColumn('action', function($pubs){
$btn = '<div style="float:right">
<i class="fas fa-book" ></i><i class="fas fa-edit" ></i></div>';
return $btn;
})
->make(true);
}
The route is defined as
Route::get('testData/{id}','DataTablesController#testData')->name('testData');
I just cannot see the way around it. Help is greatly appreciated!
I have worked it out. Basically the route cannot contain a parameter, so the {id} is dropped.
I placed a drop down box above the table and amended the javascript to
ajax:{
"url": "{{ route('allJobsData') }}",
"data": function(d) {
d.operativeChoice = $('#operativeChoice').val();
}
So if there is value in the select box this is sent via the ajax request to the controller. It is then just a case of playing with the controller code with an if statement.

my GET method is not supported for this route. (for delete) Laravel 5.8

I have table view with datatables yajra . before i using datatable my delete is normaly ,but after using datatables my delete have error like this
The GET method is not supported for this route. Supported methods: DELETE.
i using route delete but its didint work . can you correct my code ?
view
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<thead>
{{-- <th>No</th> --}}
<th>Nama Alat</th>
<th>Waktu</th>
<th>User Input</th>
<th>Action</th>
<th>Edit</th>
<th>Hapus</th>
<th>Tanggal</th>
</thead>
</tr>
#push('scripts')
<script>
$(function () {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('adminshow1dt') !!}',
columns: [
{data: 'alat.nama_alat', name: 'alat.nama_alat'},
{data: 'status', name: 'pemeliharaan.status'},
{data: 'user.name', name: 'user.name'},
{data: 'action', name: 'action', orderable: false, searchable: false},
{data: 'edit', name: 'edit', orderable: false, searchable: false},
{data: 'hapus', name: 'hapus', orderable: false, searchable: false},
{data: 'created_at', name: 'created_at'},
],
});
})
</script>
#endpush
my controller and route
public function show()
{
// $pemeliharaan = Pemeliharaan::all();
// $pemeliharaan = Pemeliharaan::find($id);
$pemeliharaan = Pemeliharaan::with(['user', 'alat'])->where('status', 'harian')->get();
return view('admin.view_harian', ['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTablesh()
{
$pemeliharaan = Pemeliharaan::with(['user', 'alat'])->where('status', 'harian')->get();
return Datatables::of($pemeliharaan)
->addColumn('action', function ($pemeliharaan) {
return '<i class="glyphicon glyphicon-eye-open"></i> View Data';
})
->editColumn('edit', function ($pemeliharaan) {
return '<i class="glyphicon glyphicon-edit"></i> Edit';
})
->editColumn('hapus', function ($pemeliharaan) {
return '<i class="glyphicon glyphicon-remove-circle"></i> Hapus';
})
->rawColumns(['hapus' => 'hapus', 'action' => 'action', 'edit' => 'edit'])
->make(true);
}
Routes
Route::delete('/admin/delete1/{id}', 'adminController#destroy1' )->name('delete1');
Route::get('admin/show1', 'adminController#show')->name('adminshow1');
Route::get('admin/show1-dt', 'adminController#indexDataTablesh')->name('adminshow1dt');
can you correct this code plz ?
Try add a form to your action column, notice we have method_field "delete" and csrf_field
$c = csrf_field();
$m = method_field('DELETE');
return "<form action='admin/delete1/$pemeliharaan->id' method='POST'>
$c
$m
<button style='margin-left:10px; width: 150px;' type='submit'
class='btn btn-xs btn-danger'>
<i class='glyphicon glyphicon-remove-circle'></i> Hapus
</button>
</form>"
yaa, ok I got it actually a tag not support delete method if you want to use delete method then you have to use form else use get method in a tag.
Route::get('/admin/delete1/{id}', 'adminController#destroy1' )->name('delete1');
Hope this helps :)

Laravel Yajra DataTable - Fetch content via Ajax with supplied search parameters

After searching as to how to fill up a Yajra DataTable with data from an ajax call with user supplied search parameters, I came to this page for the official documentation.
It has a code snippet as follows...
$builder->ajax([
'url' => route('users.index'),
'type' => 'GET',
'data' => 'function(d) { d.key = "value"; }',
])
However, I cannot make anything out of it. Where does the $builder variable come from? How do I use the data received from the Ajax call to fill up the table? This page lists the callback functions with no details.
What I need
A full-blown example of how to fill up my data table with data received from an Ajax call initiated by the search button #btn_search after selecting a value from the drop-down #param.
For simplicity, lets assume that the table structure looks like...
<select id="param">
<option value="">Select </option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn_search" value="Search">Search</button>
<table>
<thead>
<tr>
<th>Serial</th>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
</table>
The controller method that returns the data...
<?php
public function getBasicData()
{
$users = User::select(['id','name','email','address']);
return Datatables::of($users)->make();
}
The user selects a value from the dropdown and clicks on the search button. In the actual scenario, several dropdowns are there to collect the search parameters. Relevant jQuery code is...
$("#btn_search").click(function() {
var param_value = $("#param").val().trim();
// make ajax call probably
});
How can I make the Ajax call inside the click handler and fill up the data table with the received data?
The $builder variable is the class id of the table that would view the information ,
Here is an example :
<table id="data" class="table table-bordered table-hover" >
<thead>
<tr class="table-head">
<th>#</th>
<th>namr</th>
<th>email</th>
<th>date</th>
<th>auth</th>
<th>control</th>
<th>control</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<th> </th>
<th> </th>
<th> </th>
<th> </th>
<th></th>
<th></th>
<th></th>
</tfoot>
</table>
and this is ajax code
<script type="text/javascript">
var lastIdx = null;
var table = $('#data').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('/adminpanel/users/data') }}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'admin', name: 'isadmin'},
{data: 'edit', name: 'edit', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
"language": {
"url": "{{ Request::root() }} /admin/cus/Arabic.json"
},
"stateSave": false,
"responsive": true,
"order": [[0, 'asc']],
"pagingType": "full_numbers",
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: 25,
fixedHeader: true,
"oTableTools": {
"aButtons": [{
"sExtends": "csv",
"sButtonText": "ملف إكسل",
"sCharSet": "utf16le"
},
{
"sExtends": "copy",
"sButtonText": "نسخ المعلومات",
},
{
"sExtends": "print",
"sButtonText": "طباعة",
"mColumns": "visible",
}
],
"sSwfPath": "{{ Request::root() }} /website/admin/cus/copy_csv_xls_pdf.swf"
},
"dom": '<"pull-left text-left" T><"pullright" i><"clearfix"><"pull-right text-right col-lg-6" f > <"pull-left text-left" l><"clearfix">rt<"pull-right text-right col-lg-6" pi > <"pull-left text-left" l><"clearfix"> '
,initComplete: function ()
{
var r = $('#data tfoot tr');
r.find('th').each(function(){
$(this).css('padding', 8);
});
$('#data thead').append(r);
$('#search_0').css('text-align', 'center');
}
});
table.columns().eq(0).each(function(colIdx) {
$('input', table.column(colIdx).header()).on('keyup change', function() {
table
.column(colIdx)
.search(this.value)
.draw();
});
});
table.columns().eq(0).each(function(colIdx) {
$('select', table.column(colIdx).header()).on('change', function() {
table
.column(colIdx)
.search(this.value)
.draw();
});
$('select', table.column(colIdx).header()).on('click', function(e) {
e.stopPropagation();
});
});
$('#data tbody')
.on( 'mouseover', 'td', function () {
var colIdx = table.cell(this).index().column;
if ( colIdx !== lastIdx ) {
$( table.cells().nodes() ).removeClass( 'highlight' );
$( table.column( colIdx ).nodes() ).addClass( 'highlight' );
}
} )
.on( 'mouseleave', function () {
$( table.cells().nodes() ).removeClass( 'highlight' );
} );
</script>
this is a full table with ajax example ,like Yajara documentation help .

Resources