DataTables allows to export data in multiple formats like – CSV, Excel, and Pdf. This is not by default enabled.
Required including some more libraries to start using it.
In this tutorial, I show how you can add export buttons in Yajra DataTable in Laravel 9.
I am assuming you have already installed and set up the Yajra DataTable package if not then you can view this tutorial.
Contents
- Add Database configuration
- Create a Table
- Create Model
- Create Controller
- Create Route
- Create View
- Output
- Conclusion
1. Add Database configuration
Open .env
file to update the database connection.
Specify the host, database name, username, and password.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=tutorial DB_USERNAME=root DB_PASSWORD=
2. Create a Table
- Create a new table
employees
using migration.
php artisan make:migration create_employees_table
- Now, navigate to
database/migrations/
folder from the project root. - Find a PHP file that ends with
create_employees_table
and open it. - Define the table structure in the
up()
method.
public function up() { Schema::create('employees', function (Blueprint $table) { $table->id(); $table->string('emp_name',60); $table->string('email',80); $table->string('gender',20); $table->string('city',100); $table->smallInteger('status',2); $table->timestamps(); }); }
- Run the migration –
php artisan migrate
- The table is been created and I added some records to it.
3. Create Model
- Create
Employees
Model –
php artisan make:model Employees
- Open
app/Models/Employees.php
file. - Specify mass assignable Model attributes – emp_name, email, gender, city, and status using the
$fillable
property.
Completed Code
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Employees extends Model { use HasFactory; protected $fillable = [ 'emp_name','email','gender','city','status' ]; }
4. Create Controller
- Create
PageController
Controller –
php artisan make:controller PagesController
- Import
Employees
Model andDataTables
. - Create 2 methods –
- index – Load
index
view. - getDataTableData – Return DataTable data.
- index – Load
Completed Code
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Employees; use DataTables; class PagesController extends Controller { public function index(){ return view('index'); } public function getDataTableData(){ $employees = Employees::select('*'); return Datatables::of($employees) ->addIndexColumn() ->addColumn('status',function($row){ if($row->status == 1){ return "Active"; }else{ return "Inactive"; } }) ->make(); } }
5. Create Route
- Open
routes/web.php
file. - Create 2 routes –
- / – Load index view.
- /getdatatabledata – Load datatable data.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PagesController; Route::get('/', [PagesController::class, 'datatableindex']); Route::get('/getdatatabledata',[PagesController::class,'getDataTableData'])->name('getDataTableData');
6. Create View
- Create
index.blade.php
file inviews/
folder. - Include jQuery, DataTable, DataTable buttons, and some extra libraries –
<!-- CSS --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css"/> <link href='https://cdn.datatables.net/buttons/2.2.3/css/buttons.dataTables.min.css' rel='stylesheet' type='text/css'> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/2.2.3/js/dataTables.buttons.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.html5.min.js"></script>
- Create
<table >
layout to initialize DataTable.
Script –
- Initialize DataTable on
#empTable
. - Set
ajax
URL toroute('getDataTableData')
. - Add
dom: 'Blfrtip',
to enable export buttons. - Using
buttons
option control buttons that need to show. - Specify button name in
extend
. Control column that needs to export usingexportOptions
by specifying their index position. - For Pdf – I am exporting the following columns – Name, Email, Gender, City, and Status.
- For CSV – I am exporting the following columns – ID, and status.
- Using
columns
option specify key names that need to be read.
Completed Code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Add CSV Excel PDF Export buttons in Yajra DataTables - Laravel</title> <!-- Datatables CSS --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css"/> <link href='https://cdn.datatables.net/buttons/2.2.3/css/buttons.dataTables.min.css' rel='stylesheet' type='text/css'> <style type="text/css"> .dt-buttons{ width: 100%; } </style> </head> <body> <div> <table id='empTable' > <thead > <tr> <td>ID</td> <td>Name</td> <td>Email</td> <td>Gender</td> <td>City</td> <td>Status</td> </tr> </thead> </table> </div> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/2.2.3/js/dataTables.buttons.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.html5.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#empTable').DataTable({ processing: true, serverSide: true, ajax: "{{ route('getDataTableData') }}", dom: 'Blfrtip', buttons: [ { extend: 'pdf', exportOptions: { columns: [1,2,3,4,5] // Column index which needs to export } }, { extend: 'csv', exportOptions: { columns: [0,5] // Column index which needs to export } }, { extend: 'excel', } ], columns: [ {data: 'id'}, {data: 'emp_name'}, {data: 'email'}, {data: 'gender'}, {data: 'city'}, {data: 'status'}, ] }); }); </script> </body> </html>
7. Output
8. Conclusion
Make sure to add all required JS libraries otherwise, buttons will not load. By default DataTable export all visible columns, but you can control it using exportOptions
.