Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Examples for combining Yajra Datatables with other Laravel packages


Examples for combining Yajra Datatables with other Laravel packages


Combining Yajra Datatables with other Laravel packages can enhance your application by leveraging the strengths of multiple packages together. Here are some examples of how you can combine Yajra Datatables with other Laravel packages:

1. Laravel Scout for Full-Text Search:

Laravel Scout provides a simple way to integrate full-text search into your Eloquent models. You can use Scout with Yajra Datatables to provide enhanced search capabilities.

php
    // Step 1: Install Laravel Scout and the desired search driver (e.g., Algolia)
    composer require laravel/scout
    composer require algolia/algoliasearch-client-php

    // Step 2: Publish the Scout configuration
    php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

    // Step 3: Set up the .env file with your search driver credentials
    SCOUT_DRIVER=algolia
    ALGOLIA_APP_ID=your-algolia-app-id
    ALGOLIA_SECRET=your-algolia-secret

    // Step 4: Add the ScoutSearchable trait to your model
    use Laravel\Scout\Searchable;

    class User extends Model
    {
        use Searchable;
    }

    // Step 5: Define the searchable fields in the model
    public function toSearchableArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }

    // Step 6: Combine Scout with Datatables in the DataTable class
    use Yajra\DataTables\Services\DataTable;

    class UsersDataTable extends DataTable
    {
        public function dataTable($query)
        {
            return datatables()
                ->collection(User::search(request('search'))->get())
                ->addColumn('action', function ($row) {
                    return '<a href="'.route('users.edit', $row->id).'" class="btn btn-sm btn-primary">Edit</a>
                            <a href="'.route('users.show', $row->id).'" class="btn btn-sm btn-info">View</a>';
                })
                ->rawColumns(['action']);
        }

        public function query(User $model)
        {
            return $model->newQuery();
        }
    }
    

2. Laravel Spatie Permissions for Role-Based Access Control:

Spatie Permissions is a powerful package for managing roles and permissions. You can combine it with Yajra Datatables to display user roles and permissions in your datatables.

php
    // Step 1: Install Spatie Permissions
    composer require spatie/laravel-permission

    // Step 2: Publish the configuration and migration files
    php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
    php artisan migrate

    // Step 3: Add the Spatie Permissions traits to your User model
    use Spatie\Permission\Traits\HasRoles;

    class User extends Authenticatable
    {
        use HasRoles;
    }

    // Step 4: Seed roles and permissions (in a seeder or artisan tinker)
    use Spatie\Permission\Models\Role;
    use Spatie\Permission\Models\Permission;

    $role = Role::create(['name' => 'admin']);
    $permission = Permission::create(['name' => 'edit articles']);
    $role->givePermissionTo($permission);

    // Step 5: Combine Spatie Permissions with Datatables in the DataTable class
    use Yajra\DataTables\Services\DataTable;

    class UsersDataTable extends DataTable
    {
        public function dataTable($query)
        {
            return datatables()
                ->eloquent($query)
                ->addColumn('roles', function ($row) {
                    return $row->roles->pluck('name')->implode(', ');
                })
                ->addColumn('permissions', function ($row) {
                    return $row->getAllPermissions()->pluck('name')->implode(', ');
                })
                ->addColumn('action', function ($row) {
                    return '<a href="'.route('users.edit', $row->id).'" class="btn btn-sm btn-primary">Edit</a>
                            <a href="'.route('users.show', $row->id).'" class="btn btn-sm btn-info">View</a>';
                })
                ->rawColumns(['action']);
        }

        public function query(User $model)
        {
            return $model->newQuery();
        }
    }
    

3. Laravel Excel for Exporting Datatables:

Laravel Excel is a package for exporting data to Excel files. You can integrate it with Yajra Datatables to allow users to export the datatable content to Excel.

php
    // Step 1: Install Laravel Excel
    composer require maatwebsite/excel

    // Step 2: Publish the configuration
    php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

    // Step 3: Create an export class
    use Maatwebsite\Excel\Concerns\FromCollection;
    use Maatwebsite\Excel\Concerns\WithHeadings;

    class UsersExport implements FromCollection, WithHeadings
    {
        public function collection()
        {
            return User::all();
        }

        public function headings(): array
        {
            return [
                'ID',
                'Name',
                'Email',
                'Created At',
                'Updated At',
            ];
        }
    }

    // Step 4: Add a route and controller method for exporting
    use Maatwebsite\Excel\Facades\Excel;

    Route::get('users/export', function () {
        return Excel::download(new UsersExport, 'users.xlsx');
    })->name('users.export');

    // Step 5: Add an export button in the Datatables view
    <button id="export" class="btn btn-success">Export to Excel</button>

    <script>
    $(document).ready(function() {
        $('#export').on('click', function() {
            window.location.href = '{!! route('users.export') !!}';
        });

        var table = $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{!! route('users.data') !!}',
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                { data: 'created_at', name: 'created_at' },
                { data: 'updated_at', name: 'updated_at' },
                { data: 'action', name: 'action', orderable: false, searchable: false },
            ]
        });
    });
    </script>
    

4. Laravel Charts for Data Visualization:

Laravel Charts is a package for creating charts. You can use it alongside Yajra Datatables to provide data visualizations based on the table data.

php
    // Step 1: Install Laravel Charts
    composer require consoletvs/charts

    // Step 2: Publish the configuration
    php artisan vendor:publish --tag=charts_config

    // Step 3: Create a chart class
    use ConsoleTVs\Charts\Classes\Chartjs\Chart;

    class UserChart extends Chart
    {
        public function __construct()
        {
            parent::__construct();

            $this->labels(['January', 'February', 'March', 'April', 'May']);
            $this->dataset('Users by month', 'line', [3, 2, 1, 4, 3]);
        }
    }

    // Step 4: Create a controller to pass data to the chart
    use App\Charts\UserChart;

    public function index(UserChart $chart)
    {
        return view('users.index', ['chart' => $chart->build()]);
    }

    // Step 5: Display the chart in the Blade view
    <!DOCTYPE html>
    <html>
    <head>
        <title>Laravel Charts</title>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    </head>
    <body>
    <div>
        {!! $chart->container() !!}
    </div>

    {!! $chart->script() !!}
    </body>
    </html>
    

These examples show how you can combine Yajra Datatables with other Laravel packages to enhance your application. Adjust the integration based on your specific requirements and the functionalities provided by the packages you are using.