How to Use Datatables in Laravel 8 and Livewire

How to Use Datatables in Laravel 8 and Livewire

Admin
Admin・ 23 September 2021
10 min read ・ 11343 views

Laravel Livewire Datatables - In this article I will share a tutorial on how to use datatables in laravel 8 and livewire using the livewire-datatables package by mediconesystems. Livewire-datatables package is very helpful for those of us who are developing web using laravel and livewire, especially those who need a complete table view with several features such as search, export excel, filters and others.

Ok. Let's go straight to coding 👨‍💻 🚀

Step 1: Install Laravel

//via Laravel Installer
composer global require laravel/installer
laravel new laravel-livewire-datatables

//via Composer
composer create-project laravel/laravel laravel-livewire-datatables

In this first step, we need to install the latest version of laravel (currently version 8) which we will try to implement or use datatable in laravel 8 and livewire. For laravel installation, you can use the laravel installer or use composer like the example above.

Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate or generate a laravel project with the name laravel-livewire-datatables.

Wait until the installation process is complete and when it's finished, don't forget to enter the project directory using the command cd laravel-livewire-datatables.

Step 2: Setup Datatabe

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_livewire_datatables
DB_USERNAME=root
DB_PASSWORD=

Next, create a new database for the experiment using datatables in laravel 8 and livewire. If you are using xampp as local development, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name laravel_livewire_datatables. Then don't forget to also adjust the DB_DATABASE in the .env file as in the example above.

Step 3: Setup Model & Migration

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('phone')->unique();
            $table->string('address');
            $table->string('gender');
            $table->timestamps();
        });
    }

Next, open the database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php file and change the up method to be as above. In this file, we delete some existing fields and we add phone, address, gender fields in the images table like the code above. If so, save and run the php artisan migrate command to migrate all migration files.

 protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
        'gender'
    ];

Then, open the Models/User.php file and add the phone, address and gender in the protected $fillable array as above.

Step 4: Generate Dummy Data

 public function definition()
    {
        $gender = $this->faker->randomElement($array = array ('male','female'));
        
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'phone' => $this->faker->phoneNumber(),
            'address' => $this->faker->address(),
            'gender' => $gender
        ];
    }

 

Okay, now we create dummy data to populate the users table which we will then display the data using datatables in laravel 8 and livewire. Open the database/factories/UserFactory.php file, and change the method definition to be like the code above.

php artisan tinker
User::factory()->count(100)->create()

We can run or execute the UserFactory.php file using tinker. The trick, open a terminal, run the command php artisan tinker and followed by the command User::factory()->count(100)->create() like the code above. This command will create 100 dummy data for the users table.

Step 5: Install Datatables Package

composer require mediconesystems/livewire-datatables

Well, this is the important point. We will install the livewire-datatables package via composer. Run the command as above on the terminal.

Optional

php artisan vendor:publish --provider="Mediconesystems\LivewireDatatables\LivewireDatatablesServiceProvider"

If you want to change the appearance of the blade and apply your own style, run the artisan vendor:publish command as above. Datatables views will be published to resource/livewire/datatables. And the livewire-datatables.php config file contains the default time and date formats used.

Step 6: Install Livewire

composer require livewire/livewire

After installing laravel and creating a database, we continue by installing livewire in our laravel project. Run the command as above to install livewire.

Step 7: Generate Livewire Components

php artisan livewire:datatable users-table --model=user

In the seventh step, run the command as above to generate the livewire component with the target User model. With this command, we will have a livewire file located in app/Http/Livewire/UsersTable.php and already included with the public property $model.

CLASS: app/Http/Livewire/UsersTable.php

Step 8: Setup Components

<?php

namespace App\Http\Livewire;

use App\Models\User;
use Mediconesystems\LivewireDatatables\Http\Livewire\LivewireDatatable;
use Mediconesystems\LivewireDatatables\Column;
use Mediconesystems\LivewireDatatables\NumberColumn;
use Mediconesystems\LivewireDatatables\DateColumn;

class UsersTable extends LivewireDatatable
{
    public $model = User::class;

    public function columns()
    {
        return [
            NumberColumn::name('id')
                ->label('ID')
                ->defaultSort('asc')
                ->sortBy('id'),

            Column::name('name')
                ->label('Name'),

            Column::name('email')
                ->label('Email'),

            Column::name('phone')
                ->label('Phone'),

            DateColumn::name('created_at')
                ->label('Created at')
        ];
    }
}

Next, we need to setup the livewire component that we generated in the previous step. Open the file app/Http/Livewire/UsersTable.php and change the existing code to be as above. Here, we set the columns that we want to display in the datatables, namely the column id, name, email, phone and created at. In the columns method, we also use the NumberColumn, Column and DateColumn classes, for that we also need to use these traits in this file.

Step 9: Setup View

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 8 Livewire Datatables</title>
        @livewireStyles
        <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container mx-auto">
            <h1 class="py-2 text-xl text-center">Laravel 8 Livewire Datatables</h1>
            <div class="py-4">
                <livewire:users-table/>
            </div>
        </div>
    </body>
    @livewireScripts
</html>

And finally, we setup a view to display data from the users table into datatables. Open the welcome.blade.php file, then change the existing code to be like the code above. Here we use tailwindcss, why? because by default this livewire-datatables package does use tailwindcss classes for styling. Don't forget to also include @livewireStyles and @livewireScripts scripts from Livewire. Then for the livewire component, we use the users-table component.

Testing

laravel 8 livewire datatables example

Okay, until here we have both learned how to use datatables in laravel 8 and livewire using the livewire-datatables package in a very easy way. To see the results, run the laravel project with the command php artisan serve and then open the laravel project in the browser. Then the result will be like the image above.

How to add a search feature?

To add a search feature, you can do this by adding a searchable() method in the column that you want to use as a parameter in the search.

Example:

 public function columns()
    {
        return [
            NumberColumn::name('id')
                ->label('ID')
                ->defaultSort('asc')
                ->sortBy('id'),

            Column::name('name')
                ->label('Name')
                ->searchable(),

            Column::name('email')
                ->label('Email')
                ->searchable(),

            Column::name('phone')
                ->label('Phone')
                ->searchable(),

            DateColumn::name('created_at')
                ->label('Created at')
        ];
    }

For an example of how to add a search feature to livewire-datatables, see the code above. In the code above, a search feature with name, email and phone parameters will be added.

How to add filters?

To add a data filter feature in livewire datatables, you can do this by adding the filterable() method in the column where you want to add a filter.

Example:

Column::name('name')
          ->label('Name')
          ->searchable()
          ->filterable(),

How to add excel export feature?

To add an excel export feature in livewire-datatable is quite easy, by adding an exportable property in the livewire script component.

Example:

<livewire:users-table exportable/>

Is there a simpler way?

For basic usage, can use livewire-datatable component in blade view and provide targeted model.

Example:

<livewire:datatable
    model="App\Models\User"
    include="id, name, email, phone, address, created_at"
    dates="created_at"
    searchable="name, email, phone"
    exportable
    />

For an example of a basic script using livewire datatables, see the sample code above. With this code, the target model is User.php and the data that we want to display to the datatables is id, name, email, phone, address and created_at (for created_at data, we use the dates format). In addition, with this code we also add a search feature with name, email and phone parameters and add an excel export feature.

using datatables in laravel 8 and livewire

If we use datatables in livewire with basic usage code like the example above, we no longer need a livewire component like UsersTable.php that we generated at the beginning of this article. To try it, please delete or rename the UsersTable.php file, then open it in the browser again, then the result is the same as the picture above.

Enough for articles on how to use datatables in Laravel 8 and Livewire this time, for more complex uses, please visit the repository and the official website at the link below. Hopefully this article can be useful, good luck and see you in the next article.👋

 

📖 Explore the official repository: livewire-datatables

🌐 Official Site: livewire-datatables.com

Tinggalkan Komentar
Loading Comments