DATATABLES IN LARAVEL

Datatables+Laravel

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

Step by step to Implement the DataTables in the Laravel project.

You will need the following:-

Note:- If you are a beginner follow this entire guide or if you have already developed a project skip the basic setup & implementation.

Open CMD Terminal and install Laravel run the following command:

composer create-project laravel/laravel example-app

Go to the project root directory and open your IDE i.e Visual Studio Code

cd example-app

Start your Apache and MySQL database, go to the PHPMyAdmin Panel, and create a database.
Add your database credentials in the .env file of your Laravel application like:-

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

After successfully database connection, we need some demo data to store in the database and make some configuration and changes. here we will insert some fake data into the MySQL database table. Follow the steps below:-

To Create a Model, Migration, and Controller use the following command:

php artisan make:model -mcr Contact

Models are in the app/models/
Controllers are in the app/controllers/
migrations are in the database/migrations/
Note:- You can delete all unnecessary migrations

Open the contact migration file which we have created recently and we need to write some code.

database/migrations/**_create_contacts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("email");
            $table->string("phone");
            $table->string("city");
            $table->string("country");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void {
        Schema::dropIfExists('contacts');
    }
};

Open the database seeder file and type the below code to generate dummy records. The database seeder file is in the database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Contact;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder {
    /**
     * Seed the application's database.
     */
    public function run(): void {
        for ($i = 0; $i < 200; $i++) {
            $contact = new Contact();
            $contact->name = fake()->name();
            $contact->email = fake()->email();
            $contact->phone = fake()->phoneNumber();
            $contact->city = fake()->city();
            $contact->country = fake()->country();
            $contact->save();
        }
    }
}

Migrate the table and run the seeder together using this command:

php artisan migrate --seed

Setup DataTables and fetch data from the database

To install the Yajra Box Laravel datatables library:-

composer require yajra/laravel-datatables-oracle:"^10.3.1"

Configuration

  • This step is optional if you are using Laravel 5.5+
  • Open the file config/app.php and then add the following service provider. and restart your IDE for reloading the emmet abbreviations — optional
'providers' => [
    // ...
    Yajra\DataTables\DataTablesServiceProvider::class,
],

After completing the step above, use the following command to publish configuration & assets:

php artisan vendor:publish --tag=datatables

Reading data and manipulating using datatables.

routes/web.php: Create the following routes.

<?php

use App\Http\Controllers\ContactController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::view('/contacts', 'contact');
Route::get('/contacts/ajax_list', [ContactController::class, 'ajax_list'])->name('contact.ajax_list');

app/Http/Controllers/ContactController.php: For handling logical operations.

<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use Illuminate\Http\Request;

class ContactController extends Controller {
    public function ajax_list() {
        $contacts = Contact::select(
            'contacts.id',
            'contacts.name',
            'contacts.email',
            'contacts.phone',
            'contacts.city',
            'contacts.country',
        );

        return datatables($contacts)->make(false);
    }
}

Create a file with the name contact.blade.php in resources/views

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="//cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <title>Document</title>
</head>

<body>
    <table id="myTable">
        <thead>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>City</th>
            <th>Country</th>
        </thead>
    </table>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="//cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

    <script>
        $(document).ready(function() {
            $("#myTable").DataTable({
                ordering: true,
                processing: true,
                searchable: true,
                serverSide: true,
                ajax: `{{route('contact.ajax_list')}}`
            })
        })
    </script>
</body>

</html>

To start the development server run the following command:

php artisan serve
Open this link in your browser and view the dataTables working.
http://127.0.0.1:8000/contacts

Conclusion:

  • If you have any error or issue related to concern leave us a comment below.
  • This is the basic implementation of DataTables, how to server-side rendering data.
  • Visit the official DataTables page to learn more. https://datatables.net/manual/installation

Leave a Comment

Your email address will not be published. Required fields are marked *