How to Set Up Yajra DataTables in Your Laravel Project

Published on January 13, 2025 by Aman K Sahu

Yajra DataTables is an excellent package for integrating jQuery DataTables with Laravel. It simplifies handling large sets of data in a table with built-in search, pagination, sorting, and more. In this guide, we’ll show you how to set up Yajra DataTables in your Laravel project.

1. Install Yajra DataTables

You can install Yajra DataTables through Composer. Make sure your Laravel project is set up before starting the installation.

Install Yajra DataTables:
1. Run the following command in your terminal:
   composer require yajra/laravel-datatables-oracle:"~10.0"
2. After installation, the package is ready to use.
                        

2. Publish the Configuration File

This step is optional, but it’s a good practice to publish the configuration file to customize the DataTables settings.

Publish Configuration:
1. Run the following command in your terminal:
   php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
2. This will create the datatables.php configuration file in the config directory.
                        

3. Using Yajra DataTables

After installing the package, you can easily use it to display dynamic data tables. Here’s how you can use DataTables in your controllers and views.

Fetching Data

Fetch Data for DataTable:
1. In your controller, use the DataTables facade:
   use Yajra\DataTables\Facades\DataTables;
2. Return the data in the controller:
   public function index()
   {
       $users = User::query();
       return DataTables::of($users)->make(true);
   }
3. In the view, use the DataTable JavaScript:
   
ID Name Email

4. Customize Your DataTable

You can customize your DataTable further by enabling features like searching, sorting, and pagination directly from the configuration file or inline in your view.

Customize DataTable:
1. To add sorting or searching, use the `order` or `searching` parameters in your DataTable initialization:
   $('#users-table').DataTable({
       processing: true,
       serverSide: true,
       ajax: 'https://codeforcrack.com',
       order: [[0, 'asc']],  // Sort by the first column (ID)
       searching: true       // Enable search functionality
   });
                        

5. Test Your Setup

After setting up Yajra DataTables, visit the page where the table is rendered to ensure it works correctly. Test pagination, sorting, and searching functionalities to verify everything is set up properly.

More Blogs