I'm pretty new to Laravel. I want to hide the Action column of the Yajra Datatable for specific users using Gates based on their roles.
I have been able to hide the buttons in the controller, but I want to hide the entire action column in the blade file so the users will not see it at all.
I have tried this
Jquery Codes
var table = $('.cdata-tables').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('clients.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'location', name: 'location'},
{data: 'description', name: 'description'},
{data: 'testimonial', name: 'testimonial'},
#can('view-actions'){data: 'action', name: 'action', orderable: false, searchable: false}#endcan,
],
columnDefs: [
{
render: function (data, type, full, meta) {
return "<div class='text-wrap width-200'>" + data + "</div>";
},
targets: [3]
}
]
});
HTML Codes
<table class="table table-striped table-bordered responsive cdata-tables" style="width:100%">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Location</th>
<th>Description</th>
<th>Testimonial</th>
#can('view-actions')
<th width="100px">Action</th>
#endcan
</tr>
</thead>
<tfoot>
<tr>
<th>No</th>
<th>Name</th>
<th>Location</th>
<th>Description</th>
<th>Testimonial</th>
#can('view-actions')
<th width="100px">Action</th>
#endcan
</tr>
</tfoot>
</table>
Controller codes
public function index(Request $request)
{
if ($request->ajax()) {
$data = Client::latest()->get();
$this->user = Auth::user();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '';
if ($this->user->can('view-actions')){
$btn = '<i class="p-1 zmdi zmdi-edit"></i>';
$btn = $btn.' <i class="p-1 zmdi zmdi-delete"></i>';
};
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('admin.pages.client');
}
I just keep getting "Processing..." when I load the file on the browser on the Datatable. Please help out.
Related
I am trying to display all User (Where status is = 1) Data from database into DataTable using Yajra Package in Laravel but it always displays this error:
DataTables warning: table id=userTrashBin - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
When I check the response (In Developer's tools > Network Tab) it does not have any or it show Failed to load response data:
Here's my datatable() inside the UserController.php:
public function datatable()
{
$data = User::where('status', '=', 1)->get();
return DataTables::of($data)
->addColumn('action', function($data){
$url_edit = url('user/'.$data->id.'/edit');
$url_deact = url('user/deactivateUser/'.$data->id);
$url = url('user/'.$data->id);
$view = "<a class = 'btn btn-primary' href = '".$url."' title = 'View'><i class = 'nav icon fas fa-eye'></i></a>";
$edit = "<a class = 'btn btn-warning' href = '".$url_edit."' title = 'Edit'><i class = 'nav icon fas fa-edit'></i></a>";
$delete = "<button data-url = '".$url_deact."' onclick = 'deleteData(this)' class = 'btn btn-action btn-danger' title = 'Deactivate'><i class = 'nav-icon fas fa-trash-alt'></i></button>";
return $view."".$edit."".$delete;
})->editColumn('user_type', function($data){
$dataUser = User::find($data->id)->first();
$returnStr = "";
if($dataUser->hasRole('A')){
$returnStr = "Administrator";
}else{
$returnStr = "Employee";
}
return $returnStr;
})
->rawColumns(['action'])
->make(true);
}
Here's the script file in index.blade.php:
$("#userTable").DataTable({
responsive:true,
processing:true,
pagingType: 'full_numbers',
stateSave:false,
scrollY:true,
scrollX:true,
autoWidth: false,
ajax:"{{ url('user/datatable') }}",
columns:[
{data:'first_name', name: 'first_name'},
{data:'last_name', name: 'last_name'},
{data:'email', name: 'email'},
{data:'user_type', name: 'user_type'},
{data:'action', name: 'action', searchable: true, sortable:true},
]
});
The route for user/datatable inside web.php:
Route::get('user/datatable', 'UserController#datatable')->name('user/datatable')->middleware('role:A');
And finally the index.blade.php file where the userTable is located:
<table id="userTable" class="table table-bordered table-striped" data-toggle = "table1_" style = "width: 100%;">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>E-Mail Address</th>
<th>User Type</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>E-Mail Address</th>
<th>User Type</th>
<th>Action</th>
</tr>
</tfoot>
</table>
I don't know what causes the error and how to fix it for now because it doesn't have any response data or other error/s that will give me a hint.
I asked this question twice but didn't get any answer, I have two tables: Country and Region so to get all regions you must select country_id which I did with normal table but how can I do this using ajax
thank you in advance
Model of Region:
public function getRegionsByCountryID($countryID)
{
return $this
->leftJoin('countries', $this->table.'.country_id', '=', 'countries.id')
->select
(
$this->table.'.*',
'countries.name as country_name'
)
->where('country_id','=',$countryID)
->orderBy('id','asc')
->get();
}
Jquery
$.ajax({
url:"{{ route('get-regions') }}",
type: 'GET',
data: {
'country_id': country_id
},
success: function(data){
},
});
});
Controller
public function getData(Request $request)
{
$data = $this->SourceData->getRegionsByCountryID($request->input('country_id'));
return Datatables::of($data)
->addIndexColumn()
->addColumn('Actions', function($data) {
return '....';
})
->rawColumns(['Actions'])
->make(true);
}
Blade
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered datatable">
<thead>
<tr>
<th>Id</th>
<th>No</th>
<th>Name</th>
<th>Country</th>
<th>Avaliable</th>
<th width="150" class="text-center">Action</th>
</tr>
</thead>
</table>
</div>
</div>
i have to show the data in a form of datatable i use YajraBox Laravel Datatable to do that but it displayed in JSON format
/*Route code*/
Route::get('/editing','TlController#modif')->name('modif');
/*the Controller code*/
public function modif(){
return DataTables::of(Weekends::query())->make(true);
}
/*View code*/
#extends('layouts.master')
#section('containers')
<table class="table table-bordered" id="weekends-table">
<thead>
<tr>
<th>idm</th>
<th>fday</th>
<th>sday</th>
<th>id</th>
<th>updated_at</th>
<th>created_at</th>
</tr>
</thead>
<script>
$( document ).ready(function() {
$('#weekends-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('modif') !!}',
columns: [
{ data: 'idm', name: 'id' },
{ data: 'fday', name: 'first day of weekend' },
{ data: 'sday', name: 'second day of weekend' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
</script>
#endsection
this is how it represents the data:
https://i.imgur.com/ACjPm5a.png
As first commentor said, try to add this after <thead> if it will work, also don't forget the closing </table> tag:
<tbody>
<tr>
<td colspan="6">No data.</td>
</tr>
</tbody>
<tr>
<th>idm</th>
<th>fday</th>
<th>sday</th>
<th>updated_at</th>
<th>created_at</th>
</tr>
There are 5 parameters in your js and you have 6 parameters in .
You should have exact amount of parameters passed in your js and inside tag of your table. :)
I couldn't find any questions like this. All other questions are not using the Bootstrap datatables like me - they built their own table.
My Laravel 5.8 application returns currently a list of users in a searchable datatable. The problem is, that it's returning ALL users at once, so the page loads really slow since the application has a lot of users.
My routes\web.php:
Route::get('/admin/customers', 'Admin\CustomerController#renderPage')->name('admin.customers');
My app\Http\Controllers\Admin\CustomerController.php:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use ConsoleTVs\Charts\Facades\Charts;
use App\User;
class CustomerController extends Controller
{
public function renderPage() {
$customers = User::get();
return view('pages.admin.customers')->with([
'customers' => $customers
]);
}
}
My table in the view resources\views\pages\admin\customers.blade.php gets generated like this (I've removed the not relevant HTML code):
<!-- Bootstrap -->
<link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- Datatables -->
<link rel="stylesheet" href="/css/dataTables.bootstrap.min.css">
<div class="table-responsive">
<table class="table table-condensed table-hover" id="customers-table">
<thead>
<tr>
<th>#</th>
<th>First name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
</thead>
<tbody>
#foreach($customers as $customer)
<tr>
<td>{{ $customer->id }}</td>
<td>{{ $customer->first_name }}</td>
<td>{{ $customer->last_name }}</td>
<td>{{ $customer->email }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- Datatables -->
<script src="/js/jquery.dataTables.min.js"></script>
<script src="/js/dataTables.bootstrap.min.js"></script>
<script>
// Datatable settings
$(document).ready(function() {
$('#customers-table').DataTable({
"language": {
"lengthMenu": "Show _MENU_ entires per page",
"search": "Search:",
"decimal": ".",
"thousands": ",",
"zeroRecords": "No entries found.",
"info": "Showing entries _START_ to _END_ of total _TOTAL_",
"infoEmpty": "No entries available.",
"infoFiltered": "(filtered from _MAX_ total entries)",
"paginate": {
"first": "First",
"last": "Last",
"next": "Next",
"previous": "Previous"
}
}
});
} );
</script>
So the question is: What do I need to update to what in order to add support for pagination?
Instead of rendering the html on the server, try to load the DataTable via Ajax.
HTML
<table id="data-table" class="table table-striped table-bordered dt-responsive nowrap dataTable no-footer dtr-inline collapsed">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>E-Mail</th>
<th>Action</th>
</tr>
<tfoot></tfoot>
</table>
JavaScript
const table = $('#customer-table').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
'url': 'customers/list',
'type': 'POST'
},
'columns': [
{'data': 'id'},
{'data': 'first_name'},
{'data': 'last_name'},
{'data': 'email'},
{
'orderable': false,
'searchable': false,
'data': null,
'render': function (data, type, row, meta) {
// render custom html
return '<button type="button" class="btn btn-info">Edit</button>';
}
}
],
});
PHP
On the server-side take the POST request parameters and build a dynamic query (with the QueryBuilder).
Then map the result set into a DataTable compatible JSON response:
The controller action
// Build dynamic query
// ...
// Fetch result set
// ...
return response()->json([
'recordsTotal' => $count,
'recordsFiltered' => $count,
'draw' => $draw,
'data' => $rows,
];
More details about the json response: DataTable Server-side processing
public function renderPage() {
$customers = DB::table('users')->paginate(15);
return view('pages.admin.customers')->with([
'customers' => $customers
]);
}
I have this table,
<table class="table is-fullwidth" id="users-table">
<thead>
<tr>
<th> </th>
<th> ID </th>
<th> FIRST NAME </th>
<th> LAST NAME </th>
<th> EMAIL </th>
<th> ROLE </th>
</tr>
</thead>
<tfoot>
<tr>
<th> </th>
<th> ID </th>
<th> FIRST NAME </th>
<th> LAST NAME </th>
<th> EMAIL </th>
<th> ROLE </th>
</tr>
</tfoot>
</table>
and dataTable javascript in my index.blade.php
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'systemusers/data',
columnDefs: [ {
orderable: false,
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]],
columns: [
{ data: 'select', name: 'select' },
{ data: 'id', name: 'id' },
{ data: 'first_name', name: 'users.first_name' },
{ data: 'last_name', name: 'users.last_name' },
{ data: 'email', name: 'users.email' },
{ data: 'role', name: 'roles.role' },
]
});
})
</script>
and this method in my controller
public function anyData()
{
$users = UserRole::selectRaw('users.id, users.first_name, users.last_name, users.email, roles.role')
->join('users', 'users.id', '=', 'user_roles.user_id')
->join('roles', 'roles.id', '=', 'user_roles.role_id');
return Datatables::of($users)
->addColumn('select', 'systemusers::data-table.checkbox')
->make(true);
}
and for data-table\checkbox.blade.php the content is this,
<input type="checkbox" name="" value="">
This is based on the documentation found here
https://yajrabox.com/docs/laravel-datatables/master/add-column and some example here https://datatables.yajrabox.com/eloquent/add-edit-remove-column
but when I look at the output, this was the result.
I print the checkbox html code, My question is how to render that into checkbox?
You can try {!! '<input type="checkbox" name="" value="">' !!} instead of {{ '<input type="checkbox" name="" value="">' }}
Since you are using the select extension and the checkbox is supposed to work along with that, you really not need to provide a checkbox yourself.
Just add className: 'select-checkbox' to the first column, i.e
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'systemusers/data',
columnDefs: [{
orderable: false,
targets: 0,
className: 'select-checkbox' //<--- here
}],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [
[1, 'asc']
],
columns: [
{ data: 'select', name: 'select' },
{ data: 'id', name: 'id' },
{ data: 'first_name', name: 'users.first_name' },
{ data: 'last_name', name: 'users.last_name' },
{ data: 'email', name: 'users.email' },
{ data: 'role', name: 'roles.role' },
]
});
See https://datatables.net/extensions/select/examples/initialisation/checkbox.html