Your Guide to Laravel Excellence

Using Tailwind, Flowbite and Simple-DataTables in Laravel

Using Tailwind, Flowbite and Simple-DataTables in Laravel

Presenting data efficiently is critical, especially when dealing with large sets of records like user management systems or e-commerce platforms. Laravel, paired with front-end tools like Flowbite and Tailwind CSS, offers a powerful way to handle tables, and integrating Simple-DataTables. we will guide you through implementing these tools step-by-step, helping you build a dynamic, responsive, and highly interactive table within your Laravel application.

Introduction to Simple-Data Tables, Tailwind CSS and Flowbite

Simple-Data Tables is a lightweight, vanilla JS library for creating interactive data tables. It provides features like sorting, searching, and pagination (the process of dividing a document into discrete pages) out of the box, making it an ideal choice for applications where you need to display large sets of data.

Tailwind CSS is a highly customizable, utility-first CSS framework that simplifies styling with a clean and flexible syntax.

Flowbite extends the functionality of Tailwind CSS by offering pre-built components, including modals, dropdowns, and tables.  By combining these three tools, you can quickly create responsive, interactive data tables in your Laravel project.

Setting Up the Laravel Environment

npm install simple-datatables --save

npm install flowbite --save

Now we will integrate Flowbite with Tailwind CSS. Update your tailwind.config.js file to include Flowbite as a plugin:

// tailwind.config.js

module.exports = {
    content: [
      './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
      './storage/framework/views/*.php',
      './resources/views/**/*.blade.php',
      "./node_modules/flowbite/**/*.js",
    ],

    plugins: [
      require('flowbite/plugin')({
        datatables: true,
      }),
    ],
}

Using Laravel Seeders to Populate Data

Before testing the functionality of our data table, we need some dummy data to work with. This is where Laravel Seeders come in handy. Seeders allow you to populate your database with sample data for testing or development purposes. First, create a seeder using the Artisan command:

php artisan make:seeder UserSeeder

In the newly created UserSeeder.php file, define how many users you'd like to generate using Laravel factories. Here’s an example that creates 1,000 users:

public function run()
{
     \App\Models\User::factory(1000)->create();
}

Next, run the seeder:

php artisan db:seed --class=UserSeeder

This command will populate your database with 1,000 user records. You can then access this data in the users.index view, which will be displayed in the Simple-DataTables table you’ve set up. If you need factories to generate random users, ensure the UserFactory is defined like this:

public function definition()
{
    return [
        'name' => $this->faker->name(),
        'email' => $this->faker->unique()->safeEmail(),
        'email_verified_at' => now(),
        'password' => bcrypt('password'),
        'remember_token' => Str::random(10),
    ];
}

With the seeder and factory in place, you'll have plenty of sample data to test and display within your table.

Installing and Configuring Simple-DataTables

Now we will configure Simple-DataTables in your project. To do this, create a JavaScript file (e.g., dataTable.js) and import Simple-DataTables:

// resources/js/dataTable.js

import { DataTable } from "simple-datatables";
document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById("data-table")) {
        const dataTable = new DataTable("#data-table", {
            header: true,
            searchable: true,
            sortable: true,
            perPage: 10,
            perPageSelect: [5, 10, 20, 50],
            firstLast: true,
        });
    }
});

Now import the necessary libraries  in your app.js file:

// resources/js/app.js

import './bootstrap';
import 'flowbite';
import './dataTable';

The setup above ensures that when the document is loaded, the Simple-DataTables functionality will be applied to any table with the id="data-table". Optimizing Performance with Pagination When dealing with thousands of records, it's important to optimize performance by limiting the number of items displayed on each page. Laravel makes pagination (the process of dividing a document into discrete pages) easy. In your controller copy the code:

public function index(Request $request)
{
    $users = User::paginate(50);
}

Using User::paginate(50) limits the results to 50 users per page, and Simple-DataTables can handle pagination on the front end. This way, even if you have 1,000 users, the page will load quickly and users can browse through the data easily.

Styling Tables Using Flowbite and Tailwind CSS

Now that Simple-DataTables is functional, let’s style the table with Tailwind CSS. Here's a basic table structure in Blade (Laravel’s templating engine:

<table id="data-table" class="min-w-full leading-normal">
    <thead>
        <tr>
            <th class="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">#</th>
            <th class="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Name</th>
            <th class="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Email</th>
            <th class="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Action</th>
        </tr>
    </thead>
    <tbody>
        <!-- Example user row (replace with actual data) -->
        <tr>
            <td class="px-5 py-5 border-b border-gray-200 bg-white text-sm">1</td>
            <td class="px-5 py-5 border-b border-gray-200 bg-white text-sm">John Doe</td>
            <td class="px-5 py-5 border-b border-gray-200 bg-white text-sm">johndoe@example.com</td>
            <td class="px-5 py-5 border-b border-gray-200 bg-white text-sm flex">
                <a href="#" class="text-green-600 hover:text-green-900">View</a>
                <a href="#" class="ml-3 text-blue-600 hover:text-blue-900">Edit</a>
                <form method="POST" action="#" onsubmit="return confirm('Are you sure?');" class="ml-3">
                    <button type="submit" class="text-red-600 hover:text-red-900">Delete</button>
                </form>
            </td>
        </tr>
        <!-- Empty state if no users -->
        <tr>
            <td colspan="4" class="px-5 py-5 text-center">No users found.</td>
        </tr>
    </tbody>
</table>

Here, Tailwind CSS is used to style each table row, making it responsive and clean. The @forelse Blade directive ensures that the table displays users from the database, or a message if no users are found.

Conclusion

By integrating Simple-DataTables, Flowbite, and Tailwind CSS with Laravel, you can create efficient, visually appealing tables with advanced features like sorting, searching, and pagination. These tools work seamlessly together, allowing you to display large datasets without sacrificing performance or usability.

Recommeded Posts

Soft Deletes in Laravel: Using withTrashed() and onlyTrashed() in Eloquent Queries

Soft Deletes in Laravel: Using withTrashed() and onlyTrashed() in Eloquent Queries

Soft Deletes in Laravel: Using withTrashed() and onlyTrashed() in Eloquent Queries

1 month ago Read article →
Per-Second Rate Limiting in Laravel 11

Per-Second Rate Limiting in Laravel 11

Per-Second Rate Limiting in Laravel 11

1 month ago Read article →
New in Laravel 12: Eager Loading, Attribute Scopes, and fromJson

New in Laravel 12: Eager Loading, Attribute Scopes, and fromJson

Discover the new features in Laravel 12! Learn about automatic eager loading, easier query scopes with PHP attributes, and the new Collection::fromJson() method

1 month ago Read article →
Faster Query with `whereIntegerInRaw` Method

Faster Query with `whereIntegerInRaw` Method

Faster Query with `whereIntegerInRaw` Method

1 month ago Read article →