Install Datatable via npm in Laravel 8
Hello everyone, in this article, we will see how we can install datatable using NPM in Laravel 8.Before moving forward let’s know a bit about NPM.
All about NPM
- The name npm (Node Package Manager) stems from when npm first was created as a package manager for Node.js.
- All npm packages are defined in files called package.json.
- The content of package.json must be written in JSON.
- At least two fields must be present in the definition file: name and version.
- npm can manage dependencies.
- npm can (in one command line) install all the dependencies of a project.
We will follow the below steps to install datatable
- Install Npm
- Install Datatable
- Add Code in webpack
- Add code in App.js
- Add code in App.css
- Compile the asset
- Call the datatable
Step:1 Install Npm
Open the command panel from your project root folder and enter the below command, it will node modules packages.
Npm i
Step: 2 Install Datatable
Now we will install bootstrap 4 datatable by using the below command
npm install --save datatables.net-bs4
Step: 3 Add Code in webpack
We will need 2 files from DataTable to be compiled by Laravel Mix
.
This is the default webpack.mix.js
that ships with Laravel. We will include the javascript file into resources/js/app.js
and css file into resources/sass/app.scss
.
Add the below code in your webpack
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
Step:4 Add code in app.js
Add the below code in app.js to compile boostrap 4 datatable
require('datatables.net-bs4');
Step:5 Add code in app.css
Add the below code in app.css to compile datatable css
@import '~datatables.net-bs4/css/dataTables.bootstrap4.css';
Step: 6 Compile the asset
To compile the asset we can to it in two way the first way we can use npm run watch , if you want to regular changes in your app.js or app.css file, second way when you are done with your changes and want’s to go for production then use npm run prod. You can use either of them to see the changes.
npm run prod
npm run watch
Step: 7 Call the datatable
Now we have the DataTable package compiled into both app.js
and app.css
which you be found in your public
folder.
The last part is to call the .DataTable()
function.
Note: don’t add the below code in your head to call datatable
<script>
$(document).ready(function () {
$('table').DataTable();
});
</script>
Result
If you confusion feel free to comment, please rate me 5 if your like the post