How to trim a string in a yajra datatable used a raw query in laravel - 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.

Related

Load DataTable where select in Laravel 8 with yajra datatables

I need to load a DataTable where the input value equals the value in the database. I try to use this function but not work correctly.
Controller
public function getit(Request $request)
{
$shp_no = $request->shp_no_for_it;
$data = Item::select('*')->where('shp_no_for_it', $shp_no)->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)"
class="edit btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
Script
$('#search_button').click(function(){
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('getit') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
});
Input
<input type="title" class="form-control" id="shp_no_for_it" name="shp_no_for_it">
Route
Route::get('getit', [ItemController::class, 'getit'])->name('getit');
Look like you have not passed data in ajax. So first create a function to datatable
function itemDataTable(param={}){
dataTable = $('#itemTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('getit') }}",
type: 'get',
headers: { 'content-type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: param,
},
columns: [
{data: 'id', name: 'id'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
return dataTable;
}
Then on page load call data table
$(function () {
itemDataTable();
});
and on click search button
$('#search_button').click(function(){
var param={
shp_no_for_it:$('#shp_no_for_it').val();
}
itemDataTable(param)
});
and in controller if you are using server side processing then no need to call get() .But add following
processing: true,
serverSide: true,
and in controller
public function getit(Request $request)
{
$shp_no = $request->shp_no_for_it;
$data = Item::select('*') ->where('shp_no_for_it', $shp_no);
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'View';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
and in html table
<table class="table table-bordered data-table col-md-12" id="itemTable">

Laravel Yajra DataTable Column Sorting not proper working

Laravel Yajra DataTable Column Sorting not proper working. If I use ->get() function in Query then DataTable sorting works fine. But I don't want to use get() function because If I have more than 100 000 records then it takes too much time so I don't want to use get() in query
here is my controllers code
$deals = Deal::orderBy('updated_at', 'desc');
$searcharray = array();
parse_str($request->fromValues,$searcharray);
if(isset($searcharray) && !empty($searcharray)){
if($searcharray['filtertype'] !=''){
$deals->where("deal_isApproved",'=',$searcharray['filtertype']);
}
}
$detail_data = $deals;
// print_r($deals);
return Datatables::of($detail_data)
->addColumn('action', function ($data) {
$btn .= '<a class="dropdown-item" href="'.route('admin.deals.edit',$data->id).'" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-edit text-primary"></i> Edit</a>';
$btn .= '<a deal_id="'.$data->id.'" class="dropdown-item deleteDeal" href="#" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-trash-alt text-danger"></i> Delete</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
here is my datatable initialize in blade file
var dataTable = $('#example_laravel').DataTable({
//lengthMenu: getPageLengthDatatable(),
processing: true,
serverSide: true,
order: [],
searchDelay: 500,
"scrollX": "auto",
// responsive: true,
// // "responsive": true,
// "lengthChange": false,
// "autoWidth": false,
ajax: {
url: '{{ route("admin.deals.filter")}}',
type: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (data) {
data.fromValues = $("#filterdealtype").serialize();
},
},
columns: [
{data: 'SrNo', //try with data: 'SrNo' OR data: 'id',
render: function (data, type, row, meta) {
// return meta.row + meta.settings._iDisplayStart + 1;
return meta.row + 1;
}, searchable: false, sortable: false
},
{data: 'deal_title', name: 'deal_title'},
{data: 'deal_desc',
render: function (data, type, row, meta) {
var data = decodeHTMLEntities(data);
var data = data.replaceAll("href=\"","href=\"http://");
return '<div style="width: 340px; word-wrap: break-word;">'+data+'</div>';
},
},
{data: 'deal_price', name: 'deal_price'},
{data: 'deal_retail_price', name: 'deal_retail_price'},
{data: 'deal_percent_off', name: 'deal_percent_off'},
{data: 'deal_img',
render: function (data, type, row, meta) {
if(data){
return '<img id="myImg" src="{{ asset('') }}'+data+'" height="100px" width="100px">';
}else{
return '';
}
}
},
{data: 'deal_start_date', name: 'deal_start_date'},
{data: 'action', name: 'action', searchable: false, sortable: false},
],
});
output I get be like below image
I solve another problem related to sorting... I share answer of this for helping to other people,
Actually when I define orderby in controller than when I click on Datatable Column for sorting then it was not sorting, because when we click on column than it pass two times different different orderby field so its not works,
Solution of Problem
$deals = Deal::select('*');
if($request->order ==null){
$deals->orderBy('created_at', 'desc');
}
& Another problem about wrong sequence of sorting data issue faced because of wrong datatype in DataBase table...
So, Please also verify Datatype of Database
I hope its helps to you...
& thanks to you #ibrahim-dogan this guy for answer me about wrong Datatype...
thank you

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.

I need the data ,according to the type I send

My view blade that displays the data of all types but I need the specific type only, where i send it by ajax: "{{ route('taxonomies.json',type) }}".How do I send the type that I want from the given type?
<div class="table">
<table id="taxonomyTable">
<thead>
<tr>
<th>SN</th>
<th>Title</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="quickModal" tabindex="-1" role="dialog" aria-labelledby="quickModal" aria-hidden="true">
</div>
<input type="hidden" id="type" value="{{ $type }}" />
and the js is:
<script>
$(document).ready(function () {
var type = $('#type').val();
$('#taxonomyTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('taxonomies.json') }}",
columns: [
{
data: 'id',
render: function (data, type, row) {
return '<strong> #' + data + '</strong>';
}
},
{
data: 'title', name: 'title',
render: function (data, type, row) {
return '<strong>' + data + '</strong>';
}
},
{
data: 'parent', name: 'parent',
render: function (data, type, row) {
return '<strong>' + data.title + '</strong>';
}
},
{
data: 'type', name: 'type',
render: function (data, type, row) {
return '<strong>' + data.type+ '</strong>';
}
},
{
data: 'status',
render: function (data, type, row) {
return data === 'Active' ? '<button class="btn btn-outline-success btn-update-status" data-id="' + row.id + '">Active</button>' : '<button class="btn btn-xs btn-outline-danger btn-update-status" data-id="' + row.id + '">Inactive</button>';
}
},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
and my route is:
Route::get('/taxonomies/taxonomy-json/{type}', 'Admin\TaxonomyController#taxonomyJson')->name('taxonomies.json');
and my TaxonomyController has:
public function taxonomyJson()
{
$taxonomy = Taxonomy::with('parent')->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
The code mentioned above displays all of the types in the data but I only need the data of given type.Like my types are category, tag, videos,slider,etc and I need the data of types category only.
How can I fetch it?
Change You Input Hidden tag to which include whole route with it's parameters
<input type="hidden" id="type" value="{{ route('taxonomies.json', ['type' => $type]) }}" />
Now, In Your Ajax call pass input hidden type value directly to ajax as url.
var type_url = $('#type').val();
ajax: type_url
This way you don't have to worry about passing dynamic param. value to JS code from PHP code.
& In Your Controller Function
public function taxonomyJson($type=null)
{
$taxonomy = Taxonomy::with('parent')
if ($type) {
$taxonomy = $taxonomy->where('type', $type);
}
$taxonomy = $taxonomy->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
From your question as far I understood that you want filtered data, in order to get filtered data you needed to pass a filter type which you must use to filter your query. Here is an example for you
if ($request->ajax()) {
$users = User::select(
'users.id',
'users.name',
'users_details.first_name',
'users_details.last_name',
'users.email',
'users.membership_no',
'users.is_active',
'users.created_at'
)
->leftJoin('users_details', 'users.id', '=', 'users_details.users_id')
->where('user_group', '<>', 'admin')
->where(function ($query) use ($request) {
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
if (isset($genery) && $genery) {
$query->where('users_details.genre', $genery);
}
if (isset($varsitySession) && $varsitySession) {
$query->where('users_details.varsity_session', $varsitySession);
}
if (isset($yearOfPassing) && $yearOfPassing) {
$query->where('users_details.year_of_passing', $yearOfPassing);
}
if (isset($department) && $department) {
$query->where('users_details.department', $department);
}
if (isset($bloodGroup) && $bloodGroup) {
$query->where('users_details.blood_group', $bloodGroup);
}
if (isset($membership) && $membership) {
$query->where('users_details.membership', $membership);
}
if (isset($request->requested) && $request->requested == 0) {
$query->where('users.membership_no', $request->requested);
}
})
->get();
return Datatables::of($users)
->editColumn('name', function ($users) {
return ($users->first_name) ? $users->first_name . ' ' . $users->last_name : $users->name;
})
->editColumn('is_active', function ($users) {
return ($users->is_active) ? 'Active' : 'De-active';
})
->editColumn('membership_no', function ($users) {
return ($users->membership_no) ? $users->membership_no : 'Not Assigned';
})
->editColumn('created_at', function ($users) {
return $users->created_at->toDayDateTimeString();
})
->make(true);
}
Here you can see that I'm generating a query with where clause which are generated from request data
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
Here genere,varsity_session,year_of_passing,department,blood_group,membership are my filter data I'm sending with request.
here is my data table code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
processing: true,
serverSide: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data': function (d) {
d.genere = $("#genere").val();
d.varsity_session = $("select[name = varsity_session]").val();
d.year_of_passing = $("select[name = year_of_passing]").val();
d.department = $("select[name = department]").val();
d.blood_group = $("input[name = blood_group]").val();
d.membership = $("select[name = membership]").val();
d.paymentStatus = $("select[name = paymentStatus]").val();
d.requested = $("select[name = requested]").val();
}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});
And my Static Html code
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="display compact dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Membership No</th>
<th>Status</th>
<th>Versity Session</th>
<th>Due Amount</th>
<th>Paid Amount</th>
<th>Created At</th>
<th>Last Transaction</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- /.col-lg-12 -->
</div>

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