How to limit results per page in Yajra datatables - laravel

How can I limit the results of data each page in Yajra datatables? Currently I'm using the code below:
Controller
return Datatables::of(collect($results))->make(true);
The $results variable is just an array of data from database.
JS
$('table.dataTableAjax').DataTable({
"processing": true, // Make this true, to show the "Processing" word while loading
"serverSide": true,
"paging": true,
"pageLength": 10,
"ordering": false, // Make this false, to disable sorting
"ajax": "..."
});
Example data from server
{
"data":[
{ "name": "Bob", "Age": 30 },
{ "name": "Billy", "Age": 33 },
{ "name": "Megan", "Age": 31 }
]
}
So for example, the first page should load 10 rows, next page 10 rows again, and so on. But what's happening is it loads the 5000+ rows, and just cutting them into 10 table rows in client side which affects the performance of the application. Any idea?

I ended up by just adding these code below, and not using yajra for the functionality.
$limit = request('length');
$start = request('start');
$query->offset($start)->limit($limit);
return response()->json([
"draw" => intval(request('draw')),
"recordsTotal" => intval(User::count()),
"recordsFiltered" => intval($total_filtered),
"data" => $results
]);
Everything works fine, and loads faster. I didn't notice that datatables actually throws requests to the laravel end point (route).

this is working for me and shorter code
return Datatables::of($data)->setTotalRecords(500)->make(true);
setTotalRecords() is a best answer for your looking for

Related

VueJs not sending data via Inertia to Laravel?

I have question it seems like when I try to send some data via Inertia I dont recieve any in Laravel for some reason any suggestion? Can it have to do something with the fact that the object is proxy object ?
Here are some images:
dd() in php controlelr
console.log() of the object before beeing sent via Inertia
Code of how I send the data + the console log right before sending it
UPDATE:
This is how I add page object to array of pages:
this.Pages.push({
"name": "Untitled",
"icon": "home",
"order": order,
"sections": [],
"DisplayName":true,
"Banner":"Medium",
"Published":"Published",
"DisplayLogo":true,
"media":{
'BackgroundImage': null,
'LogoImage': null,
'BackgroundImageHeight': null,
'LogoImageHeight': null,
'BackgroundImageStyle': {
"value": []
},
"LogoImageStyle": {
"value": []
},
}
});
This is my inertia form:
saveForm: {
applications: [],
},
This is whole save() method:
Save() {
if(this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] != undefined){
if(this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].data == undefined){
this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] = {
"Pages": this.Pages,
"media": this.media,
"name": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].name,
"active": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].active,
};
}
else{
this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] = {
"Pages": this.Pages,
"media": this.media,
"name": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].name,
"active": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].active,
"data" : this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].data,
};
}
}
this.saveForm.applications = toRaw(this.localProduct.translation.applications);
console.log(this.saveForm);
Inertia.post(this.route(`product.translations.applications`,{translation: this.localProduct.translation.id}),this.saveForm);
},
The applications should be array, the mobile_label should be also array.As it is.
!!!IMPORTANT ALSO!!!
All of this code worked before the project started to shift to vue js 3 and I suppose many libraries had to be updated/exchanged for others.
According to Inertia's documentation the first parameter expected when using Inertia.post() is a URL. Does all of this.route(`product.translations.applications`,{translation: thislocalProduct.translation.id}) return a URL?
To anyone who's having same problem check your array/object assiging to your variables there could be the mistake like in mine I fixed mine with this:
this.saveForm.applications = toRaw(this.localProduct.translation.applications);
var fixed = Object.assign({},this.localProduct.translation.applications);
Inertia.post(this.route(`product.translations.applications`,{translation: this.localProduct.translation.id}),fixed);

Why is my elasticsearch update_by_query timing out?

I am using the Javascript library and and trying to perform a rather large update on documents. I have changed the timeout value on the query itself as well as the client object and am still getting a timeout that seems to be 2 minutes. Below is the query.
const arrayOfStrings = [...]; // This array could be between 10-12k elements in size
await elasticClient.updateByQuery({
index: "main-index",
refresh: true,
conflicts:"proceed",
script: {
lang: "painless",
source: "ctx._source.status = \"1\"; ctx._source.entities = []; for(term in params.array) ctx._source.entities.add(term);",
params: {
"array": arrayOfStrings
}
},
query: {
"term": {
"parent_id": 'dgd39gd3-db3dg23879-d893gdg38-e23ed' // There could be upwards of 5000 documents that match this criteria
}
},
timeout: "5m"
});
Also on the elastic client, I have requestTimeout set to '5m' as well. I can understand why this particular query may be timing out as its applying a 12k element array to a field on 5k documents. However I dont understand why the query is timing out after only 2 minutes when I have timeout values set that are longer.
What you need to do here is to run the update by query asynchronously
await elasticClient.updateByQuery({
index: "main-index",
refresh: true,
conflicts:"proceed",
waitForCompletion: false <---- add this setting
And then you can follow the progress of the task running asynchronously.

Laravel Fractal add success message to response

Is it possible to add a success message to a JSON response using Fractal? I would like the structure to look like the following
{
"success": true,
"message": "Clients found",
"_metadata": {
"total_count": 2
},
"data": {
"clients": [
]
}
}
I have written the following code to return the data
$response_data = fractal()
->collection($person_array)
->transformWith(new ResponseTransformer())
->toArray();
Do I need to create a new serialiser to get this format? I have been following this documentation https://packagist.org/packages/spatie/fractalistic but there is no option to add extra key values such as success: true.
I also want to use this format for all my API responses, is it possible to create a generic Transformer which returns what ever array data I pass into it instead of creating a Transformer per Model?
Laravel fractal allows to add meta data to collections :
fractal()
->addMeta([
'status' => [
'success' => true,
'code' => 1,
'message' => 'Test'
]
])
Resulting JSON output
"meta": {
"status": {
"success": true,
"code": 1,
"message": "Test"
}
}

how to make the data ascending/descending using vue js datatable (parent-child)

My question is about the parent-child DataTable used in vue.js, I want to show the data in the descending format. But it's just allowing the filter for columnname:name.
this.datatable = ele.DataTable( {
"data": [],
"columns": [
{
"className":'details-control',
"orderable":false,
"data":"name",
"defaultContent": '',
},
]
} );
here above in data the name is passed, its just filtering through the name. I also want it according to one more column in my database table.so it should display the name also in descending format.

Pagination not working - Datatables 1.10.9

I am using server side processing (AJAX requests) to get my table with data. I am getting the correct data. However, pagination is not working. The table info on the bottom left says Showing 1 to 10 of 182 entries and the bottom right shows the page numbers as well but the table shows all the possible records in the first page itself. Here's the code I use:
$(tableId).DataTable({
"paging": true,
"scrollX": true,
"filter": false,
"serverSide":true,
"columns": [
{"data":'transaction_id'},
{"data":'merchant_id'},
{"data":'merchant_provider_id'},
{"data":'transaction_uuid'},
{"data":'transaction_status_type'},
{"data":'transaction_payment_method'},
{"data":'transaction_amount'},
{"data":'transaction_amount_aud'},
{"data":'transaction_aud_exchange_rate'},
{"data":'transaction_amount_usd'},
{"data":'transaction_usd_exchange_rate'},
{"data":'transaction_currency'},
{"data":'transaction_created'},
{"data":'transaction_processed'},
{"data":'transaction_settled'},
],
"ajax": {
"url": requestUrl,
"data": values
}
});
When using server side processing with Datatables, the server side handles dividing the entries into pages. The ajax request will include parameters for offset (start) and page length (length). The server side must use these parameters to select and return the correct entries for each page.

Resources