DEV Community

Alpha Olomi
Alpha Olomi

Posted on • Edited on

How to get started with DataTables in Laravel 9

Hello, there!

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

Image description

To start

Create a new project


Using the laravel installer we can create a new project.



laravel new datatables
cd datatables


Enter fullscreen mode Exit fullscreen mode

Setup database and ENV configuration


We will use a simple SQLite database.

Create a database file.



touch database/database.sqlite


Enter fullscreen mode Exit fullscreen mode

Update .env to point to database file.

Comment all other DB_* lines.



DB_CONNECTION=sqlite


Enter fullscreen mode Exit fullscreen mode

Install package and publish assets




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


Enter fullscreen mode Exit fullscreen mode

Setup Laravel UI




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


Enter fullscreen mode Exit fullscreen mode

Install Datatables.net assets




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


Enter fullscreen mode Exit fullscreen mode

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


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



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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

Compile assets




yarn run production


Enter fullscreen mode Exit fullscreen mode

Create controller and DataTable class




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


Enter fullscreen mode Exit fullscreen mode

UsersController



namespace App\Http\Controllers;

use App\DataTables\UsersDataTable;

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


Enter fullscreen mode Exit fullscreen mode

UsersDataTable



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');
    }
}


Enter fullscreen mode Exit fullscreen mode

Update app layout


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



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


Enter fullscreen mode Exit fullscreen mode

Create users index file


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



@extends('layouts.app')

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

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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

Register users route


Update routes/web.php.



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


Enter fullscreen mode Exit fullscreen mode

Create dummy data using Tinker




php artisan tinker

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


Enter fullscreen mode Exit fullscreen mode

Access Users DataTables


Start the development server, run



php artisan serve


Enter fullscreen mode Exit fullscreen mode

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

Happy Coding!

Top comments (0)