DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Multiple Laravel DataTables in one view β€” as a Service Implementation
Anlisha Maharjan
Anlisha Maharjan

Posted on • Originally published at anlisha.com.np on

Multiple Laravel DataTables in one view β€” as a Service Implementation

Hi, If you are new to yajra/laravel-datatables follow the installation or new to Laravel DataTables as a Service Implementation, I recommend you to have a look at it here.

We’ll be rendering 2 data-table in 1 view quick and easy using latest version of yajra/laravel-datatables as a service.

Step 1 β€” Define Route

Add the below code in routes/web.php file to instantiate the route. Note the extra route dashboard.user and dashboard.notice.

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

Route::get('user',[App\Http\Controllers\DashboardController::class, 'getUser'])->name('dashboard.user');

Route::get('notice',[App\Http\Controllers\DashboardController::class,'getNotice'])->name('dashboard.notice');
Enter fullscreen mode Exit fullscreen mode

Step 2 β€” Generate and Set Up Controller

Run command to create DashboardController.

php artisan make:controller DashboardController
Enter fullscreen mode Exit fullscreen mode

Add code in app/Http/Controllers/DashboardController.php file. Note the two DataTable Service Class implementation.

Step 3β€” Generate DataTable Service

Run command to create UserDataTable and NoticeDataTable.

php artisan datatables:make User
php artisan datatables:make Notice
Enter fullscreen mode Exit fullscreen mode

Place the below code in app/DataTables/UserDataTable.php ** and **app/DataTables/NoticeDataTable.php

Note on line 48, minifiedAjax(route(β€˜dashboard.user’))? It calls the route defined earlier to fetch user.

Step 4β€” Setup Blade View

Head over to the resources/views folder and create a dashboard/index.blade.php file and insert the below code in it.

@extends('layouts.app')
@section('content')

<div class="row">
<div class="table-responsive">
  {{$userDataTable->table(['width' => '100%', 'id'=>'user-data-table', 'class' => 'table table-striped dataTable'])}}
 </div>
<div class="table-responsive">
  {{$noticeDataTable->table(['width' => '100%', 'id'=>'notice-data-table', 'class' => 'table table-striped dataTable'])}}
 </div>
</div>
@endsection

@push('scripts')
{{$userDataTable->scripts()}}
{{$noticeDataTable->scripts()}}
@endpush
Enter fullscreen mode Exit fullscreen mode

And That’s it. Enjoy!

The post Multiple Laravel DataTables in one view β€” as a Service Implementation first appeared on Anlisha Maharjan.

Top comments (0)

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.