Yajra Datatables Package for Laravel deosnt work properly with laravel 5.2 - datatable

I have installed yajra/laravel-datatables-oracle "~6.0" package for supporting server-side datatables in laravel 5.2 with MySql as database.
i'm trying to display the datatable of users:
//routes.php
Route::group(['middleware' => ['web'], 'prefix' => 'user'], function () {
Route::get('/index', 'UserController#index')->name('user.index');
});
and here is my controller:
//UserController.php
public function index()
{
return view('user.index');
}
public function indexData()
{
$users = User::select(['id', 'name', 'email', 'created_at', 'updated_at'])->get();
return Datatables::of($users)->make();
}
the view:
// user\index.blade.php
#extends('layouts.base')
#section('additional_styles')
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
#endsection
#section('additional_scripts')
<!-- DataTables -->
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script>
$('#users-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": '{!! route('user.index') !!}',
"columns": [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'updated_at', name: 'updated_at'}
]
});
</script>
#endsection
#section('main-content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-body">
<table class="table table-bordered" id="users-table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
but the datatable doesn't work properly. after processing to render tha data, it show me an alert that the response have invalid JSON format and says to see datatables.net/tn/1. I have tried to see whithin the developer tools of chrome to see the response but i couldnt!
any idea about the issue ?

now its work in laravel 5.2.31,
` Route
Route::get('datatables',['uses'=>'DatatablesController#getIndex', 'as' => 'datatables']);
Route::get('datatables/{data}',['uses'=>'DatatablesController#anyData', 'as' => 'datatables.data']);
Controller
public function anyData()
{
$users = User::select(['id', 'name', 'email', 'created_at', 'updated_at'])->get();
return Datatables::of($users)->make();
}
JS
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! url('datatables/data') !!}'
});`

Related

Laravel 5.8 and datatable form validation

I am using Laravel 5.8 and Yajra datatable package.
I have to build a dynamic form from the controller (it works well).
After submitting the form, when the validation fails, I want to display the old values in the form.
Display the form/datatable and validation work fine. I need the way to display the old values.
Controller (build the form) (just an excerpt as it works fine)
if (request()->ajax())
{
return datatables()
->of($memberships)
->addIndexColumn()
->addColumn('amount', function($data) use ($membership, $amounts) {
$link = '<input type="text" id="membership_id[]" name="membership_id[]" value="' . $data->id . '" style="width:100px" class="form-control">';
$link .= '<input type="number" id="amount[]" name="amount[]" value="">';
return $link;
})
->rawColumns(['amount'])
->make(true);
}
return view('my_blade', compact('memberships', 'id'));
My question here is How to set the value attribute in the amount input field when the validation fails?
my_blade (display datatable form) (just an excerpt as it works fine)
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="POST" id="my_form" action="{{ route('my_submit_route') }}">
#csrf
<input type="text" id="id" name="id" value="{{ $id }}">
<table id="my_datatable" class="table table-hover table-striped table-responsive">
<thead class="crud-header">
<tr>
<th>No</th>
<th>Name</th>
<th>Description</th>
<th>Status</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="form-group row">
<div class="col text-center">
<button type="submit" class="btn btn-primary">
Save
</button>
</div>
</div>
</form>
</div>
</div>
#endsection
#section('script')
<script>
$(document).ready(function() {
/* Start Datatable */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.noConflict();
$('#my_datatable').DataTable({
iDisplayLength: 100,
serverSide: true,
processing: true,
ajax: {
url: "{{ route('my_route', ['id' => $id]) }}",
type: 'GET',
},
columnDefs: [
{className: "dt-center", targets: "_all"}
],
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false},
{data: 'name', name: 'name'},
{data: 'given_name', name: 'given_name'},
{data: 'amount', name: 'amount'}
],
order: [[1, 'desc']]
});
/* End Datatable */
});
</script>
#endsection
My validation works fine. Just don't know how to display the old value when validation fails
My Controller (to process form submit)
/* get the array of membership IDs */
$membershipIDs = $request->membership_id;
$validate_array = [];
/* Loop through membership for validation */
for($i = 0; $i < count($membershipIDs); $i++)
{
$validate_array['amount.'. $i] = 'sometimes|nullable|numeric|gte:0';
}
$validator = Validator::make($request->all(), $validate_array);
if ($validator->fails())
{
/* Get the array of amounts */
$amounts = $request->amount;
// How to manage here to return in the form and display the old values and the error message on the failed fields?
}
else
{
//Process the form;
}
My question: How to manage in the controller to return in the form and display the old values and the error messages on the failed fields?
I also use the following for validation, the validation works well but I cannot display the old values in the form after the validation fails.
$this->validate($request, $validate_array);
Thanks
Try this in your controller:
if ($validator->fails()) {
return back()->withInput()->withErrors($validator);
}
Not sure if this also works in Laravel 5. But an alternate to this is:
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
Which works in Laravel 5

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

Yajra Datatable custom Model Attribute

I'm using Yajra Datatables for Laravel and it won't show the custom attribute for my User model. This is my User model:
protected $appends = ['sum_work_hours'];
public function work_hours()
{
return $this->hasMany(WorkHour::class);
}
public function getSumWorkHoursAttribute()
{
return $this->work_hours->sum('hours_total');
}
And this is in Controller:
public function showHours()
{
return view('hour');
}
public function getHoursDatatable()
{
$users = User::select(['name', 'email', 'sum_work_hours']);
return Datatables::of($users)->make();
}
And in view:
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">All Working Hours</div>
<div class="panel-body">
<table id="users-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Sum Work Hours</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'http://127.0.0.1:8000/datatables/get_hours_datatable',
columns: [
{ data: 'name' },
{ data: 'email' },
{ data: 'sum_work_hours' }
]
});
});
</script>
And this is what I get:
What could be wrong?
The problem was in my Controller
public function getHoursDatatable()
{
// this line was wrong
$users = User::select(['name', 'email', 'sum_work_hours']);
return Datatables::of($users)->make();
}
It should have been like this:
$users = User::with('work_hours')->get();
Now I get the results in my table.

Add delete button in Data table with Laravel

I' trying to add delete button in Data table column but it doesn't work. but my edit button works perfect. here i have post my QusLINK
edit button works perfect but delet button only errors
public function getRowDetailsData(PslCall $call)
{
$crews = Crew::Where('call_id',$call->id)->get();
return Datatables::of($crews)
->addColumn('action', function ($crew) {
return '<span class="glyphicon glyphicon-edit" data-toggle="tooltip" title="Edit"aria-hidden="true"></span>
<form action="{{ route(\'crews.destroy\', $crew->id)}}" method="POST"><input type="hidden" name="_method" value="DELETE">
<button type="submit" class="btn-xs form-btn confirmation-callback" data-placement="left"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
</form>';
})
->editColumn('id', 'ID: {{$id}}')
->removeColumn('id')
->editColumn('arrival_date', function ($crew) {
return $crew->arrival_date ? with(new Carbon($crew->arrival_date))->format('d-M-Y h:i') : '';
})
->filterColumn('arrival_date', function ($query, $keyword) {
$query->whereRaw("DATE_FORMAT(created_at,'%m/%d/%Y') like ?", ["%$keyword%"]);
})->make(true);
}
My Table like this
<table class="table table-striped table-bordered table-hover datas" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>NAME</th>
<th>GENDER</th>
<th>TYPE</th>
<th>ARRIVAL /DEPARTURE</th>
<th>ACTION</th>
</tr>
</thead>
</table>
again my script like this
var table = $('.datas').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('calls/'.$call->id.'/row-details-data') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"searchable": false,
"data": null,
"defaultContent": '<span class="btn btn-xs glyphicon glyphicon-download"></span>'
},
{data: 'crew_name', name: 'crew_name'},
{data: 'gender', name: 'gender'},
{data: 'crew_type'},
{data: 'arrival_date', "render":function(data, type, row){
switch(row.crew_type) {
case 'ONSIGNER' : return 'Arrival : '+ row.arrival_date; break;
case 'OFFSIGNER' : return 'Depart : '+ row.arrival_date; break;
default : return 'N/A';
}
}},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
} );
May
{!! Form::open(array('url' => '/crews/'.$crew->id, 'method' => 'delete')) !!}
<button type="submit" class="btn-xs form-btn confirmation-callback" data-placement="left"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
!! Form::close() !!}

Resources