laravel, eloquent where condition get result in yajra datatable - php

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>

Related

Hide the action column in Yajra datatables using gates

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.

Laravel 5.8: Eloquent Pagination for Bootstrap Datatable

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
]);
}

Get Multiple Check Box Values to View Data From MYSQL in TWIG

This is my Controller:
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$deployments = $this->getDoctrine()
->getRepository('AppBundle:Billing')
->findAll();
return $this->render('default/index.html.twig', array('deployments' => $deployments));
}
/**
* #Route("/results", name="resultsPage")
*/
public function resultsAction(Request $request)
{
return $this->render('default/results.html.twig');
}
/**
* #Route("/route/action/save", name="route-action-save")
* #Method({"POST"})
*/
public function checkBoxAction(Request $request){
return $arrayTenantID = $request->request->get('allvals');
}
The snippet of code below is in my index.html.twig file
<form>
<div id="stuffTable">
<table class="table table-hover" action="" method="post"> <thead>
<script src="{{ asset('bundles/public/js/libs/jquery.min.js') }}"> </script>
<tr> <th>Tenant ID</th>
<th>Tenant</th>
</tr>
</thead>
<tbody>
{% for stuff in deployments %}
<tr>
<th scope="row">
<input type="checkbox" value="{{stuff.tenantID}}" id="tenantID">
<label for="tenantID">{{stuff.tenantID}}</label>
<td>{{stuff.tenantName}}</td>
</th>
</tr>
{% endfor %}
</tbody>
</div>
</table>
<textarea id="textArea"></textarea>
The table (image below) shows the TenantID and TenantName, but how do I use the checkbox so after clicking the "submit" button, another table will show data of the checked TenantIDs only?
To make my question a bit more clear,how do I save the TenantID values after they have been checked, so I can use it to Query the same table? I am using Doctrine to query.
<script>
function updateTextArea() {
var allVals = [];
$('#stuffTable :checked').each(function() {
allVals.push($(this).val());
});
$('#textArea').val(allVals);
sendData(allVals);
}
$(function() {
$('#stuffTable input').click(updateTextArea);
updateTextArea();
});
function sendData(allVals) {
$.ajax({
url: "{{ path('route-action-save') }}",
type: 'POST',
dataType: 'json',
data: {"allVals": allVals},
success: function(response){
alert("hello");
}
});
}
This is my JavaScript and it seems to give me an error:
http://localhost:8000/route/action/save 500 (Internal Server Error)
Thank you in advance.
Try this, you have the table with tenants Id:
<head>
<script src="jquery-2.2.4.min.js"></script>
</head>
<table class="table table-hover"> <thead>
<tr> <th>Tenant ID</th>
<th>Tenant</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">
<input type="checkbox" name="tenantNum[]" value="1000"> 1000</th>
<td>tenant_Name</td>
</tr>
<tr>
<th scope="row">
<input type="checkbox" name="tenantNum[]" value="1001"> 1001</th>
<td>tenant_Name</td>
</tr>
<tr>
<th scope="row">
<input type="checkbox" name="tenantNum[]" value="1002"> 1002</th>
<td>tenant_Name</td>
</tr>
</tbody>
</table>
<button type="button" id="tenant_id_button" >Ok</button>
Now, You could use Jquery and get multiple checkboxes values (checkboxes that you have been clicked) and after that, send it to php file (process_tenant.php)
<script>
$(document).ready(function () {
$('#tenant_id_button').click(function () {
//Get checked Id
var array_tenant_id = new Array();
$("input:checked").each(function () {
array_tenant_id.push($(this).val());
});
//array_tenant_id = ["1000", "1002"]
$.ajax({
url: "process_tenant.php",
method: 'POST',
dataType: 'json',
data: {"array_tenant_id": array_tenant_id},
success: function (data) {
//read response: data
}
});
});
});
</script>
Now, you will get the checkboxes values server-side (file process_tenant.php)
<?php
$array_tenant_id = $_POST['array_tenant_id'];
var_dump($array_tenant_id);
The output will be an array with checkboxes previously checked:
array(2) (
[0] => (string) 1000
[1] => (string) 1002
)
** If you use Symfony **
Include Jquery library where you have the html table or include it in your base.html.twig
<script src="{{ asset('bundles/public/js/libs/jquery.min.js') }}"> </script>
Now, send 'array_tenant_id' as parameter to your controller:
$.ajax({
url: "{{ path('route-action-save') }}",
method: 'POST',
dataType: 'json',
data: {"array_tenant_id": array_tenant_id},
In the controller:
/**
* #Route("/route/action/save", name="route-action-save")
* #Method({"POST"})
*/
public function saveSomething(Request $request) {
$array_tenant_id= $request->request->get('array_tenant_id');

Not able to display data through ajax in codeigniter

i want to show the restaurant after selecting its area from dropdown list. but my code did not show the restaurant name and the menu button of that restaurant please tell me where i did mistake
Its my model code
function select_record($table, $where = NULL)
{
$this->db->select();
if ($where) $this->db->where($where);
$this->db->from($table);
$query = $this->db->get();
// echo $this->db->last_query();
return $query->result();
}
Controller code
public function get_rests()
{
$cit_id = $this->input->post('cit_id');
$area = $this->input->post('areaID');
$where = array(
'city_id' => $cit_id,
'city_area_id' => $area
);
$data = $this->bulk->select_record('restaurant', $where);
$html = '<div class="container" id="">
<table align="centre" class="table table-condensed table-striped table-hover no-margin"style="width:70%" id="">
<thread>
<tr style="width: 56%;">
<th> No. </th>
<th style=""> Restaurant Names </th>
</tr>
</thread>
<tbody>
<th> <span value="'. $data[0]->restaurant_id . '" class="res_id"></span></th>
<th style=""> </th>
<th style=""> <span value="'. $data[0]->restaurant_name . '" class="res_id"></span> </th>
<th style="width: 1%" > </i>See Menu </th>
</tr>
</tbody>
</table>
</div>';
echo json_encode(array(
'data' => $html
));
}
Script code
function get_rests() {
var city_id = $('#city_id').val();
var area_id = $("#area_id").val();
$.ajax({
type: "POST",
url: "<?=base_url();?>index.php/Bulk_Controller/get_rests",
data: {
cit_id: city_id,
areaID: area_id
},
dataType: 'json',
cache: false,
success: function (response) {
alert(response);
$('#restaurant').html(response.data);
}
});
}
Its view code
<div id="restaurant">
</div>
when i did alert(response.data);
<div class="container" id="">
<table align="centre" class="table table-condensed table-striped table-hover no-margin"style="width:70%" id="">
<thread>
<tr style="width: 56%;">
<th>
No.
</th>
<th style="">
Restaurant Names
</th>
</tr>
</thread>
<tbody>
<th>
<span value="1" class="res_id"></span></th>
<th style="">
</th>
<th style="">
<span value="salten paper" class="res_id"></span>
</th>
<th style="width: 1%" >
</i>See Menu
</th>
</tr>
</tbody>
</table>
</div>
Please tell me where i did mistake
You are not putting the response from ajax properly. $('#restaurant').html(response.data); should be:
$('#restaurant').html(response);
Also change
url: "<?=base_url();?>index.php/Bulk_Controller/get_rests",
to
url: "<?=base_url();?>index.php/bulk_controller/get_rests",
Try the below,
You should return it rather than echo, Also you have to set the request header as json
Model:
function select_record($table, $where = NULL)
{
$this->db->select('*');
$this->db->from($table);// this should come right after select statement
if ($where) $this->db->where($where);
$query = $this->db->get();
// echo $this->db->last_query();
return $query->result();
}
Controller:
public function get_rests()
{
$cit_id = $this->input->post('cit_id');
$area = $this->input->post('areaID');
$where = array(
'city_id' => $cit_id,
'city_area_id' => $area
);
$data = $this->bulk->select_record('restaurant', $where);
$html = '<div class="container" id="">
<table align="centre" class="table table-condensed table-striped table-hover no-margin"style="width:70%" id="">
<thread>
<tr style="width: 56%;">
<th> No. </th>
<th style=""> Restaurant Names </th>
</tr>
</thread>
<tbody>
<th> <span value="'. $data[0]->restaurant_id . '" class="res_id"></span></th>
<th style=""> </th>
<th style=""> <span value="'. $data[0]->restaurant_name . '" class="res_id"></span> </th>
<th style="width: 1%" > </i>See Menu </th>
</tr>
</tbody>
</table>
</div>';
return $this->output->set_content_type('application/json')->set_output(json_encode(array(
'data' => $html,
)));
}
Script:
function get_rests() {
var city_id = $('#city_id').val();
var area_id = $("#area_id").val();
$.ajax({
type: "POST",
url: "<?=base_url();?>index.php/Bulk_Controller/get_rests",
data: {
'cit_id': city_id,
'areaID': area_id
},
dataType: 'json',
cache: false,
success: function (response) {
alert(response);
console.log(response)
$('#restaurant').html(response.data);
}
});
}

Datatables not loading

I am trying to using datatables Jquery plugin in codeingiter but its not working please help me to debug
Heres my controller where I am calling my view:
public function show_all_merchants()
{
$data["query"]= $this->details_model->get_mids();
$this->load->view('show_merchants_view',$data);
}
Heres my view:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function()
{
$('#example').dataTable
({
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : 'show_merchant_details',
'iDisplayStart' : 0,
'fnServerData': function(sSource, aoData, fnCallback)
{
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback,
'cache' : false
});
}
});
});
</script>
<table cellpadding="0" cellspacing="0" border="0" id="example">
<thead>
<tr>
<th width="20%">ID</th>
<th width="25%">First Name</th>
<th width="15%">Last Name</th>
<th width="25%">Email</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">Loading data from server</td>
</tr>
</tbody>
</table>
and heres my controller where I am loading the data Here I am loading data tables library:
function show_merchant_details()
{
$this->datatables
->select('mid, merchant_name, merchant_link,merchant_contact')
->from('merchants')
->add_column('edit', 'Edit', 'id')
->add_column('delete', 'Delete', 'id');
echo $this->datatables->generate();
}
Friends show_merchant_details() is wrking properly as i am able to see the output
In the view page I am able to see it like Loading data from server ...... (dats it)

Categories