wordpress

How to implement Yajra Datatable in Laravel ?

Datatable is an excellent pacakage for those who wants to make a normal table interactive.

The step to implement the Datatable is as follow.

You can also follow the documentation of the laravel

https://github.com/yajra/laravel-datatables

1) First of all go to your command prompt and your root folder and hit this command

composer require yajra/laravel-datatables-oracle

You can also specify the version of datatable as follow:

composer require yajra/laravel-datatables-oracle:"~9.0"

2) Then you have to go to config/app.php folder and paste the following codes

'providers' => [       Yajra\DataTables\DataTablesServiceProvider::class,] 

'aliases' => [     'DataTables' => Yajra\DataTables\Facades\DataTables::class,]

 

3) then go to the command prompt and publish the package by this code

Php artisan vendor:publish –tag=datatables

4) Now you are ready to go. Make a Model (say: Post) and its migration. Migrate the databse.

5) Make a controller by command prompt. You can also work on previously made controller. In the controller put this code.

public function getPosts()

{

$data = Post::all();

return Datatables::of($data)

->make(true);

}

NOTE: You have to include

use App\Post ;

use Datatables;

in the controller.

You should also make index() function to view the tables. In my case I have made as below:

public function index()

{

return view('backend.subject');

}

6) Now make the respective routes for view

Route::get(‘/’, ‘DatatableController@index’);

Route::get('datatable/getposts', ['as'=>'datatable.getposts','uses'=>'SubjectNoteController@getPosts']);

7) Now the last part to manage the view. Make a table with idname (say: myid)

<table id="myid">

<thead>

<tr>

<th>#</th>

<th>Title</th>

<th>Author</th>

<th>Category</th>


</tr>

</thead>

<tbody>

8) Now send the data by using ajax to the controller by this method below:

<script type="text/javascript">

$(document).ready(function() {

$('.myid).DataTable({

"processing": true,

"serverSide": true,

"ajax": "{{ route('datatable.getposts') }}",

"columns": [

{data: 'id', name: 'id'},

{data: 'title', name: 'title'},

{data: 'author', name: 'author'},

{data: 'category', name: 'category'}

]

});

});

</script>

9) Please don’t forget to include jquery in the view page. You can use the following code

<script   src="https://code.jquery.com/jquery-3.5.1.min.js"   integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="   crossorigin="anonymous"></script>

 

jaminrai

Share
Published by
jaminrai