Yarja Datatables - getting results for specific id - laravel

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.

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.

Laravel and DataTables.net

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

How to trim a string in a yajra datatable used a raw query in laravel

I have a problem on how to trim string in my datatable from a query where in used a raw query to get data from the database.
my query example is
public function data()
{
return DB::table('query_table')
->select([
DB::raw('query_table.data1 AS data1'),
DB::raw('query_table2.data2 AS data2'),
])
->join('query_table2','query_table2.query_table_id','=','query_table.id')
->where(['query_table.id' => 1])
->orderByDesc('query_table.data1')
->get();
}
from controller for my data table
public function dataDataTable()
{
$data = $this->query->data(); //query of data
return DataTables::of($data)
->addIndexColumn()
->make(true);
}
I am using datatables as view in laravel
#extends('layouts.main' , ['title' => trans('label.data.table')])
#include('includes.datatable_assets')
#push('after-styles')
#include('includes.custom_assets')
#endpush
#section('content')
<div class="card">
<div class="card-body">
<header class="card-header card-header-custom">
<h2 class="card-title" style="color: white" >{!! trans('label.table.header') !!}</h2>
</header>
<div class="" id="list-all">
<table class="display" id="templates-table">
<thead>
<tr>
<th>#lang('label.sn')</th>
<th>#lang('label.data1')</th>
<th>#lang('label.data2')</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
#endsection
#push('after-scripts')
<script type="text/javascript">
$('#templates-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('query.datatable.route') !!}',
type: 'get',
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false, width: '5%'},
{data: 'data1', name: 'data1', orderable: false, searchable: true, width: '65%'},
{data: 'data2', name: 'data2', orderable: false, searchable: true, width: '35%'},
],
</script>
#endpush
How do I trim data1 string so as can be seen with few characters in my datatable view ?
You can either do it in PHP or in Javascript:
Javascript:
$('#templates-table').DataTable({
...,
columnDefs: [{
targets: 1,
render: function (data, type, row) {
return type === 'display' && data.length > 50 ? data.substr(0, 50) + '…' : data;
}
}]
});
You can read more about it here.
PHP:
use Illuminate\Support\Str;
public function dataDataTable()
{
$data = $this->query->data(); // query of data
return DataTables::of($data)
->editColumn('data1', function ($data) {
return Str::limit($data->data1, 50);
})
->addIndexColumn()
->make(true);
}
If you don't have to show the user the full string I would use the PHP version, so your response does not get bloated.

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 :)

Resources