How to get started with DataTables in Laravel 9
Tags: webdev, laravel, datatables
Published: 2022-06-01 18:30:14

Hello, there!

In this tutorial, we will be learning how to use DataTables to display data from Laravel Application.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86bmq4l88132z044smvy.png)
 

To start

## Create a new project
------------------

Using the laravel installer we can create a new project.


```bash
laravel new datatables
cd datatables
```

## Setup database and ENV configuration
------------------------------------

We will use a simple SQLite database.


### Create a database file.

```bash
touch database/database.sqlite
```

### Update .env to point to database file.

Comment all other `DB_*` lines.

```ini
DB_CONNECTION=sqlite
```

## Install package and publish assets
----------------------------------

```sh
# install package
composer require yajra/laravel-datatables
# publish assets for buttons
php artisan vendor:publish --tag=datatables-buttons
```

## Setup Laravel UI
----------------

```sh
composer require laravel/ui --dev
php artisan ui bootstrap --auth
```

## Install Datatables.net assets
-----------------------------


```sh
yarn add datatables.net-bs5 datatables.net-buttons-bs5
```

## Register datatables.net assets in bootstrap.js and app.scss
-----------------------------------------------------------

Edit `resources/js/bootstrap.js` and add the following:

```js
require('bootstrap');
require('datatables.net-bs5');
require('datatables.net-buttons-bs5');
```

Edit `resources/scss/app.scss` and add the following:

```scss
// ...
// DataTables
@import "~datatables.net-bs5/css/dataTables.bootstrap5.css";
@import "~datatables.net-buttons-bs5/css/buttons.bootstrap5.css";
```

## Compile assets
--------------

```sh
yarn run production
```

## Create controller and DataTable class
-------------------------------------

```sh
# 
php artisan make:controller UserController
#
php artisan datatables:make Users
```

### UsersController

```php
namespace App\Http\Controllers;

use App\DataTables\UsersDataTable;

class UserController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        return $dataTable->render('users.index');
    }
}
```

### UsersDataTable

```php
namespace App\DataTables;

use App\Models\User;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Services\DataTable;

class UsersDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('action', 'users.action');
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\User $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(User $model)
    {
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->setTableId('users-table')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('Bfrtip')
                    ->orderBy(1)
                    ->buttons(
                        Button::make('create'),
                        Button::make('export'),
                        Button::make('print'),
                        Button::make('reset'),
                        Button::make('reload')
                    );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::make('id'),
            Column::make('name'),
            Column::make('email'),
            Column::make('created_at'),
            Column::make('updated_at'),
            Column::computed('action')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename(): string
    {
        return 'Users_' . date('YmdHis');
    }
}
```

## Update app layout
-----------------

Add scripts before the body end tag of `resources/views/layouts/app.blade.php`

```html
    <script src="{{ mix('js/app.js') }}"></script>
    <script src="{{ asset('vendor/datatables/buttons.server-side.js') }}"></script>
    @stack('scripts')
```

## Create users index file
-----------------------

Create new file: `resources/views/users/index.blade.php`.

```ruby
@extends('layouts.app')

@section('content')
    <div>  {{$dataTable->table()}} </div>
@endsection

@push('scripts')
    {{$dataTable->scripts()}}
@endpush
```

Create new file: `resources/views/users/action.blade.php`.


```html
<a href="" class="btn btn-primary btn-sm">Edit</a>
<a href="" class="btn btn-danger btn-sm">Delete</a>
```

## Register `users` route
--------------------

Update `routes/web.php`.

```php
// ...
use App\Http\Controllers\UserController;
// ...
Route::get('/users', [App\Http\Controllers\UserController::class,'index'])->name('users.index');
// ...
```

## Create dummy data using [Tinker](https://laravel.com/docs/9.x/artisan#tinker)
------------------------------

```php
php artisan tinker

Psy Shell v0.11.5 (PHP 8.1.5 — cli) by Justin Hileman
>>> User::factory(100)->create()
```

## Access Users DataTables
-----------------------

Start the development server, run

```sh
php artisan serve
```

In the browser open <http://localhost:8000/users>

Happy Coding!