How to use webpack and datatable on laravel?

by cortez.connelly , in category: PHP Frameworks , 2 months ago

How to use webpack and datatable on laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , a month ago

@cortez.connelly 

To use Webpack and DataTable on Laravel, follow these steps:

  1. Install Webpack: Laravel comes with Laravel Mix, which is a layer on top of Webpack. Make sure to install Laravel Mix by running the following command:
1
npm install


  1. Install DataTables: Install DataTables by running the following command:
1
npm install datatables.net


  1. Configure Laravel Mix: Open the webpack.mix.js file located in the root directory of your Laravel project. Add the following code to compile the DataTables CSS and JavaScript files:
1
2
3
4
mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .copy('node_modules/datatables.net/js/jquery.dataTables.js', 'public/js')
   .copyDirectory('node_modules/datatables.net-dt/css/jquery.dataTables.css', 'public/css');


  1. Create a DataTable: Create a new DataTable in your JavaScript file (resources/js/app.js). Here is an example of how to create a simple DataTable:
1
2
3
$(document).ready( function () {
    $('#datatable').DataTable();
});


  1. Include DataTables in your Blade file: Include the required DataTables CSS and JavaScript files in your Blade file. Add the following code to include DataTables in your Blade file:
1
2
<link href="{{ asset('css/jquery.dataTables.css') }}" rel="stylesheet">
<script src="{{ asset('js/jquery.dataTables.js') }}"></script>


  1. Initialize DataTable: Finally, initialize the DataTable in your Blade file by calling the DataTable() function on the target table element. Here is an example of how to initialize a DataTable on a table element with an ID of datatable:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<table id="datatable">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
        </tr>
    </tbody>
</table>

<script>
    $(document).ready( function () {
        $('#datatable').DataTable();
    });
</script>


That's it! You have successfully set up Webpack and DataTable on Laravel. Just make sure to run the npm run dev command to compile your assets after making any changes.