How to use HasManyThrough Relation in laravel datatable - laravel-5

I have three tables i am able to use relation between 2 tables easily. But when i am trying to access values from third table i mean trying to use hasManyThrough relation it is showing me always error. Do you have any idea how i can get value of third table column using middle table relation with first and last table.
System details
Linux
PHP 7
Laravel 5.3
Laravel-Datatables Latest Version
$('#mms-table').DataTable({
processing : true,
serverSide: true,
lengthMenu: [10,25,50,100],
order: [[1,'desc']],
ajax: '{!! url(LaravelLocalization::getCurrentLocale()."/admin/contact-management/contact-data") !!}',
columns: [
{ data: 'merchant.bank.name', name: 'merchant.bank_id', orderable: true },
{ data: 'merchant.merchant_id', name: 'merchant.merchant_id', orderable: true },
{ data: 'merchant.merchant_name', name: 'merchant.merchant_name', orderable: true },
{ data: 'contact.name', name: 'contact.name', orderable: true },
{ data: 'contact.email', name: 'contact.email', orderable: true },
{ data: 'city', name: 'city', orderable: true },
{ data: 'agent.name', name: 'agent.name', orderable: true },
{ data: 'action', name: 'action', orderable: false, searchable: false},
],
dom: 'Blfrptip',
buttons: [
{
extend: 'colvis',text: 'Show/Hide Columns'
}
],
oLanguage: {
sProcessing: "<img height='80' width='80' src='{{ url('public/images/loading.gif') }}' alt='loader'/>"
},
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
});

Related

How to pass user_id in ajax route datatable Laravel

I have a datatable in Laravel, here is my code
$(function() {
var user_id = $(this).data('user_id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
paging: true,
info: true,
autoWidth: false,
responsive: true,
processing: true,
serverSide: true,
ajax: "{{ route('detail.user', 'user_id')}}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'title',
name: 'title',
orderable: false,
},
{
data: 'content',
name: 'content',
orderable: false,
visible: false,
},
{
data: 'progress',
name: 'progress'
},
{
data: 'status',
name: 'status'
},
{
data: 'kpi',
name: 'kpi'
},
{
data: 'target_selesai',
name: 'target_selesai'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
$('body').on('click', '.detailProduct', function() {
...
});
$('#saveBtn').click(function(e) {
...
});
$('body').on('click', '.deleteProduct', function() {
...
});
});
I want to get user_id value from url parameter (ex: http://127.0.0.1:8000/detail/1000000004 ), I've tried code above, but it will return empty value.
Seems like I write wrong code to get url parameter. Because, If I change the ajax: "{{ route('detail.user', 'user_id')}}", into ajax: "{{ route('detail.user', '1000000004')}}", the program will works as expected. What sould I do? thanks in advance
You can not set variable in PHP code using JavaScript. You should not use PHP code on dynamic JavaScript code. There are 2 alternatives :
Use static path instead of Laravel route, just change ajax: "{{ route('detail.user', 'user_id')}}" to ajax: "/detail/"+user_id
Send user_id variable using Laravel blade view arg. on your controller define user_id like below:
return view('index',
['user_id', 1000000004]
);
then call it on the blade as php variable ($user_id) example ajax: "{{ route('detail.user', $user_id)}}"
be sure url in routes/web.php, provide one variable passing, ex /name-routes/{id}
and then in your controller function take the data id, function function_name($id){ }
and the last be sure format return json with format be like { data : [ name : "value name 1", name : "value_name2" ] }

Unknown paramater name when calling data in datatable

When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Here is My controller
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = Post::select(DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();
return Datatables::of($data)
->addIndexColumn()
->make(true);
}
return view('task.index',);
}
Here is my view
<script type="text/javascript">
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('team.task') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'name',
name: 'name',
orderable: false,
},
{
data: 'total',
name: 'total',
orderable: false,
},
{
data: 'finish',
name: 'finish'
},
]
});
});
</script>
When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Is something wrong in my controller or my view? thanks in advance
use this query
$data = DB::table('posts')->select('name', DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();

Can't get ID from URL Laravel

I have a datatable view that shows some post from user, I want to create a datatable with a button that can show all user post. But, when moving from all post lists to user post lists I cant get user_id from the URL.
I want to get the user_id using $request->route.
Here is my controller:-
public function index(Request $request)
{
if ($request->ajax()) {
$request->route('detail');
$data = Post::where('user_id', $this->route('detail'))->latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('detail');
}
Here is my route:-
Route::resource('detail', DetailController::class);
datatable code
var table = $('.data-table').DataTable({
paging: true,
info: true,
autoWidth: false,
responsive: true,
columnDefs: [{
"targets": [0, 2, 3, 4, 5, 6], // your case first column
"className": "text-center",
},
],
language: {
paginate: {
next: '<span class="fas fa-arrow-right"></span>', // or '→'
previous: '<span class="fas fa-arrow-left"></span>' // or '←'
}
},
oLanguage: {
"oPaginate": {
next: '→', // or '→'
previous: '←' // or '←'
},
"sLengthMenu": "Tampilkan _MENU_ Item",
"sEmptyTable": "Tidak ada data",
"sInfoEmpty": "Tidak ditemukan",
"sLoadingRecords": "Sedang memproses - loading...",
"sInfo": "Menampilkan _START_ - _END_ dari _TOTAL_ Item",
"sSearch": "Cari:",
},
processing: true,
serverSide: true,
ajax: "{{ route('detail.index') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'title',
name: 'title',
orderable: false,
},
{
data: 'content',
name: 'content',
orderable: false,
visible: false,
},
{
data: 'progress',
name: 'progress'
},
{
data: 'status',
name: 'status'
},
{
data: 'target_selesai',
name: 'target_selesai'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
If I change the $this->route('detail') into user_id value, the program will work as expected. Is there something wrong with my code? thanks in advance
Change this:-
$this->route('detail')
To:-
$request->get('details')
And your ajax method should be like this:
"ajax": {
'type': 'POST',
'url': '{{ route('detail.index') }}',
'data': {
detilas: 'your id',
},
}
your roure:
Route::post('detail', DetailController::class);

laravel datatables search in addColumn

I use laravel/datatables to list data.
I manipulated my datalist with addColumn function.
However I am not able to use search in view for added columns.
Because search is working according to database rows.
Datatables works fine but in the view search area is not working. Because there isnt any fullname row in database table.
Here you can find my codes (I want to search for fullname but I can't)
Order Model
public function getFullname()
{
return json_decode($this->getAttribute('delivery_adress'))->fullname;
}
OrderController.php
if ($request->ajax()) {
return datatables()->of(Order::query())
->addColumn('fullname', function (Order $order) {
return $order->getFullname();
})->addColumn('city', function (Order $order) {
return $order->getCity();
})->addColumn('product_id', function (Order $order) {
return $order->product->title;
})->make(true);
}
Orders Blade / Datatables code
"pageLength": 10,
processing: true,
serverSide: true,
ajax: 'orders',
columns: [
{ data: 'id', name: 'id'},
{ data: 'fullname', name: 'fullname', defaultContent: '-' , orderable: false },
{ data: 'city', name: 'city', defaultContent: '-', orderable: false },
{ data: 'product_id', name: 'product_id', className: 'd-none d-sm-table-cell', defaultContent: '-' },
{ data: 'totalPrice', name: 'totalPrice', className: 'd-none d-sm-table-cell', defaultContent: '-' },
],
edit:
Finally, I found solution
{data: 'added_column', name: 'actual_column_name'}
https://github.com/yajra/laravel-datatables/issues/139#issuecomment-275326787
Finally, I found solution
{data: 'added_column', name: 'actual_column_name'}
https://github.com/yajra/laravel-datatables/issues/139#issuecomment-275326787
Make sure to have relationship into Order model like this:
public function user()
{
return $this->belongsTo('App\User');
}
Try to update like this :
...
->addColumn('fullname', function (Order $order) {
return $order->user->fullname;
})
...
change status
serverSide : false
"pageLength": 10,
processing: true,
serverSide: false,
ajax: 'orders',
columns: [
{ data: 'id', name: 'id'},
{ data: 'fullname', name: 'fullname', defaultContent: '-' , orderable: false },
{ data: 'city', name: 'city', defaultContent: '-', orderable: false },
{ data: 'product_id', name: 'product_id', className: 'd-none d-sm-table-cell', defaultContent: '-' },
{ data: 'totalPrice', name: 'totalPrice', className: 'd-none d-sm-table-cell', defaultContent: '-' },
],

Delete button in Yajra Datatables in Laravel 5.7.9

Hallo I have the MemberController with this action:
public function anyData()
{
$members = DB::table('members')
->select(['id','email','firstname','lastname','address','zip','city','phone','mobile','work','birthdate']);
return Datatables::of($members)
->addColumn('action', function ($id) {
return 'Edit
<button class="btn" data-remote="/member/' . $id->id . '">Delete</button>
'; })->make(true);
}
This is the JS Code to get the table with the datas:
<script type="text/javascript">
var table = $('#datatable-member').DataTable({
responsive: true,
"language": {
"url": "{{ asset('/plugins/datatables/lang').'/'.Config::get('app.locale').'.json'}}"
},
processing: true,
serverSide: true,
ajax: '{{ route('member') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'firstname', name: 'firstname' },
{ data: 'lastname', name: 'lastname' },
{ data: 'address', name: 'address' },
{ data: 'zip', name: 'zip' },
{ data: 'city', name: 'city' },
{ data: 'phone', name: 'phone' },
{ data: 'mobile', name: 'mobile' },
{ data: 'work', name: 'work' },
{ data: 'birthdate', name: 'birthdate' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[1, 'asc']]
}).$('.btn[data-remote]').on('click', function (e) {alert('test') })
;
</script>
The tables shows the data correctly, the edit link and delete button appears correctly but the action (at the moment only an alert) in the delete button is not working, when i click nothing happens.
I tryied also this on the javascript but nothing changed:
$('#datatable-member').DataTable().on('click', '.btn-delete[data-remote]', function (e) {alert('test') })
From Laravel framework for delete you need to have form validation by using X-CSRF Token. Try this to send a proper request for delete if you are using Laravel resource you can use below code, but make sure your datatable edit column are using the btn-delete class, as you are right now using the btn class.
<script type="text/javascript">
var table = $('#datatable-member').DataTable({
responsive: true,
"language": {
"url": "{{ asset('/plugins/datatables/lang').'/'.Config::get('app.locale').'.json'}}"
},
processing: true,
serverSide: true,
ajax: '{{ route('member') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'firstname', name: 'firstname' },
{ data: 'lastname', name: 'lastname' },
{ data: 'address', name: 'address' },
{ data: 'zip', name: 'zip' },
{ data: 'city', name: 'city' },
{ data: 'phone', name: 'phone' },
{ data: 'mobile', name: 'mobile' },
{ data: 'work', name: 'work' },
{ data: 'birthdate', name: 'birthdate' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[1, 'asc']]
});
$('#datatable-member').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
// confirm then
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#datatable-member').DataTable().draw(false);
});
});

Resources