Get 2024 Templates Mega Bundle!14 Bootstrap, Vue & React Templates + 3 Vector Sets
Get for 99$

METRONIC LARAVEL


hello, I am trying to analyze the crud of users of metronic version laravel, I am noticing in the datatable part, that you are generating the scripts on the server side, however, there is a table.js file that also initializes the datatables, so this me It seems redundant and I don't know which one to use.


Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(

Replies (10)


Hi Desarrollo

I'd appreciate it if you could share a screenshot or provide more details about the issue you're facing. This will help me better understand the problem and guide you in the right direction.

Thanks



I will tell you in detail...

I am checking the CRUD of laravel metronic
I am interested and analyzing the use of DataTables that they implemented for their operation.

I'm noticing that everything starts in
UserManagementController
UsersDataTable
and then ends up in the view list.blade.php
{{ $dataTable->table() }}
{{ $dataTable->scripts() }}




but I'm noticing that there is a javascript file called table.js that also initializes the datatable, so I don't understand why if you're doing it from
{{ $dataTable->scripts() }}

because it reinitializes in that file javascript table.js, or is it a file that was left of bug?

Tell me how the process would be then, to be able to continue with my development, since it is not clear to me, if you are doing it from the server with UsersDataTable, or from the client in that javascript file.










basically it is in the use of the datatable, since I notice that both javascript and blade are done in both parts, clarify that for me, I hope I have been clear, waiting for a prompt response, thank you very much...



Thank you for your detailed clarifications. In the Laravel Metronic, the DataTables are primarily initialized and managed by the Yajra DataTables plugin, not the table.js file. Here's a clarification of the process:

UsersDataTable : This class is part of Yajra DataTables and is responsible for defining the DataTable configuration, columns, and querying the data from your Laravel application.

UserManagementController : This controller uses the UsersDataTable class to build and return the DataTable. It interacts with your Laravel application's data, processes queries, and returns the necessary data to the DataTable.

list.blade.php : In this Blade view file, you see {{ $dataTable->table() }} and {{ $dataTable->scripts() }}. These are provided by the Yajra DataTables package.

{{ $dataTable->table() }}: This part renders the HTML structure for the DataTable. It sets up the table structure and initializes it, but it doesn't populate it with data directly.

{{ $dataTable->scripts() }}: This includes the necessary JavaScript code to initialize and enhance the DataTable. It's where the DataTable gets initialized with features like searching, sorting, and pagination. This JavaScript code is provided by the Yajra DataTables package and is responsible for making DataTables interactive on the client side.

So, the DataTable is indeed initialized and managed on the client side using the JavaScript provided by Yajra DataTables, but the configuration and data retrieval are handled on the server side in Laravel through the UsersDataTable and UserManagementController.

Regarding the table.js file in the src folder, you're correct that it's not in use within the Laravel version of Metronic. It seems to be a remnant from the core HTML assets and can be safely removed from your Laravel project since the DataTable functionality is handled differently in Laravel Metronic. We will exclude it by default in the future updates.

I hope this clarifies the process for you. If you have any more questions or need further assistance, please feel free to ask.



Hello, thank you for the prompt response, however, the more I review the script, I have doubts due to the redundancy issue that I am seeing.

I'm noticing that they use Html Builder Event Callbacks
from the yajrabox package, which I am noticing re-initializes the table within that code from the _draw-scripts.js file

If the server is already initializing the table, why does it initialize the table again from the client through that event callbacks?

I see it as redundancy and absurd unless you clarify the reason...

the only logical thing I see there is

// Initialize KTMenu
KTMenu.init();








Hi,

The drawCallback function in DataTables is a callback function that gets executed every time the DataTables plugin performs a draw operation on the table. A "draw" operation typically happens when you change the page, apply a filter, or sort the table data.

The JavaScript code _draw-scripts.js is part of the DataTables initialization process and includes event listeners and functionality for various actions.

Initialize KTMenu: This line initializes the KTMenu, which is a part of the theme. KTMenu is responsible for dropdown menus and other UI elements. Initializing it here ensures that any dropdown menus work correctly within DataTables.

Update Button Click Event: Similar to the delete button event, this code adds a click event listener to elements with data-kt-action="update_row". When an update button is clicked, it emits an update_user event to Livewire with the associated user ID.

Livewire 'success' Event Listener: This code listens for a 'success' event emitted by Livewire. When this event is triggered, it reloads the DataTable with the ID 'users-table' using DataTables' ajax.reload() method. This is likely used to update the table after a successful action, such as deleting or updating a user.

In summary, the JavaScript code provided is not reinitializing the DataTable itself but is responsible for handling user interactions, such as deleting and updating rows, and updating the table when these actions are successful. The use of event listeners and Livewire integration allows for dynamic updates to the table without reloading the entire page.



Ok, I understand the drop-down menu, update and deletion thing perfectly.


but why does it initialize the datatables again from that _draw-scripts.js file??????

That is, I understand that the drop-down menu and everything related to the table itself must be updated, but why initialize it again in the following code:


$(function () {
window.LaravelDataTables = window.LaravelDataTables || {};
window.LaravelDataTables["users-table"] = $("#users-table").DataTable({
serverSide: true,
processing: true,
ajax: {
url: "http://127.0.0.1:8000/user-management/users",
type: "GET",
data: function (data) {
for (var i = 0, len = data.columns.length; i < len; i++) {
if (!data.columns[i].search.value)
delete data.columns[i].search;
if (data.columns[i].searchable === true)
delete data.columns[i].searchable;
if (data.columns[i].orderable === true)
delete data.columns[i].orderable;
if (data.columns[i].data === data.columns[i].name)
delete data.columns[i].name;
}
delete data.search.regex;
},
},
columns: [
{
data: "user",
name: "name",
title: "User",
orderable: true,
searchable: true,
className: "d-flex align-items-center",
},
{
data: "role",
name: "role",
title: "Role",
orderable: true,
searchable: false,
},
{
data: "last_login_at",
name: "last_login_at",
title: "Last Login",
orderable: true,
searchable: true,
},
{
data: "created_at",
name: "created_at",
title: "Joined Date",
orderable: true,
searchable: true,
className: "text-nowrap",
},
{
data: "action",
name: "action",
title: "Action",
orderable: false,
searchable: false,
className: "text-end text-nowrap",
width: 60,
},
],
dom: "rt<"row"<"col-sm-12 col-md-5"l><"col-sm-12 col-md-7"p>>",
order: [[2, "desc"]],
drawCallback: function () {
// Initialize KTMenu
KTMenu.init();

// Add click event listener to delete buttons
document
.querySelectorAll("[data-kt-action="delete_row"]")
.forEach(function (element) {
element.addEventListener("click", function () {
Swal.fire({
text: "Are you sure you want to remove?",
icon: "warning",
buttonsStyling: false,
showCancelButton: true,
confirmButtonText: "Yes",
cancelButtonText: "No",
customClass: {
confirmButton: "btn btn-danger",
cancelButton: "btn btn-secondary",
},
}).then((result) => {
if (result.isConfirmed) {
Livewire.emit(
"delete_user",
this.getAttribute("data-kt-user-id")
);
}
});
});
});

// Add click event listener to update buttons
document
.querySelectorAll("[data-kt-action="update_row"]")
.forEach(function (element) {
element.addEventListener("click", function () {
Livewire.emit(
"update_user",
this.getAttribute("data-kt-user-id")
);
});
});

// Listen for "success" event emitted by Livewire
Livewire.on("success", (message) => {
// Reload the users-table datatable
LaravelDataTables["users-table"].ajax.reload();
});
},
});
});


Isn't it supposed that you are already doing this initialization with PHP?


{{ $dataTable->table() }}
{{ $dataTable->scripts() }}



Thank you for sharing the code. The DataTable initialization code should not be placed within the `_draw-scripts.js` file.

Could you please provide information about the version you are currently using?
recommend downloading and using the latest version, which can be found at the following link:
https://devs.keenthemes.com/metronic/laravel

Here's a link to what the latest `_draw-script.js` file looks like, and as you can see, there is no DataTable initialization code included:



metronic_laravel_v8.2.0_demo1

Hello, I am using version 8.2.0
I downloaded it recently and checked again and it had that datatables initialization code in draw-scripts.js

but I just downloaded it again and it doesn't have it, even though it is the same version 8.2.0, how is this possible? They made some change that was not notified... I no longer know what to believe, please clarify that for me, anyway I will check again in depth and I will let you know if I have a question.

on the other hand because they decided to use the initialization that way and not from javascript and making a request to the server


return DataTables::of($query)->toJson();


What would be the difference for you???

I hope I am explaining it well



I apologize for any confusion. It's possible that there was a temporary issue with the package during the initial release of version 8.2.0, and it was subsequently reuploaded with the necessary changes within a few hours. These kinds of updates or corrections can happen without explicit notifications, but they are intended to ensure the stability and functionality of the product.

If you encounter any questions or issues while using version 8.2.0 or have any specific concerns, please feel free to reach out. I'm here to assist you with any inquiries or assistance you may need with the Metronic theme.



It sounds like you're comparing two different approaches to initializing DataTables in a Laravel application, specifically in the context of making a request to the server.

1) Server-Side DataTables Initialization using yajra/laravel-datatables:
https://yajrabox.com/docs/laravel-datatables/10.0/engine-eloquent

In this approach, DataTables are initialized and configured on the server-side within your Laravel application.

Data is retrieved from the database and processed on the server, and then DataTables sends a JSON response directly to the client.

DataTables on the client-side receives pre-processed data and handles rendering and interactions without making additional server requests.
The yajra/laravel-datatables package simplifies server-side DataTables implementation in Laravel and provides various features for handling complex queries and data transformations.

It's essential to follow the recommended practices outlined in the yajra/laravel-datatables documentation to ensure efficient and secure server-side data handling. These recommendations include using the package's features for handling queries, optimizing database queries, and enforcing security checks on the server.


2) Client-Side DataTables Initialization using JavaScript:

In this approach, DataTables are initialized and configured on the client-side using JavaScript.

Data is fetched from the server via an API endpoint, typically in JSON format, and DataTables handles rendering, sorting, filtering, and other interactions on the client-side.

This approach is often more responsive because it allows immediate user feedback without waiting for server responses for sorting or filtering.
It can be beneficial when you want to minimize server load and network traffic for relatively small datasets.

When implementing client-side DataTables, you should also follow best practices for client-side scripting, including efficient data loading and handling user interactions.


3) Considerations:

Data Volume: If you're dealing with a large amount of data, server-side initialization can be more efficient because it avoids sending the entire dataset to the client.

User Experience: Client-side initialization offers a more responsive user experience but may require more client-side resources.

Complexity: Server-side initialization with yajra/laravel-datatables simplifies server-side data handling but requires some server-side configuration.

Security: Server-side initialization allows you to enforce security and authorization checks on the server before sending data to the client.

The choice between these approaches depends on your project's requirements, including data volume, desired user experience, and your application's architecture. Following the recommendations in the yajra/laravel-datatables documentation ensures efficient and secure server-side data handling when using this package.


Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(
Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(