Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Datatables - Multiple tables on one view

I'm using laravel 5.4 and the latest version of yajra/laravel-datatables as a service.

I have it working fine with one datatable on a page. I want to create a dashboard of unrelated tables. Users, products, bookings etc.

I was hoping to have my controller look something like this:

public function index(ProductsDataTable $productDatatable, UsersDataTable $userDatatable)
{    
    $user = Auth::user();

    $products = $user->products;

    return view('admin.dashboard', compact('products', 'user', 'productDatatable', 'userDatatable'));
}

and in my blade do

@section('content')
{!! $productDatatable->table() !!}
{!! $userDatatable->table() !!}
@endsection

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

However this obviously doesn't work. I'm unsure how to proceed.

I tried to create a route for each datatable but wasn't sure how to reference it from my dashboard controller.

like image 770
Peck3277 Avatar asked Mar 09 '23 08:03

Peck3277


1 Answers

I'm sure there's a better way of implementing multiple tables in one view, but this is what I came up with after reviewing this. Comments/improvements would be highly appreciated.

Controller

The controller will render the tables once in the index() method but will fetch data from both the getUsers() method or getProducts() method.

// DashboardController.php

public function index(UsersDataTable $usersDataTable, ProductsDataTable $productsDataTable)
{
    return view('dashboard.index', [
        'usersDataTable' => $usersDataTable->html(),
        'productsDataTable' => $productsDataTable->html()
    ]);
}

//Gets Users JSON

public function getUsers(UsersDataTable $usersDataTable)
{
    return $usersDataTable->render('admin.dashboard');
}

//Gets Products JSON

public function getProducts(ProductsDataTable $productsDataTable)
{
    return $productsDataTable->render('admin.dashboard');
}

Routes

Add two extra routes that will be used to fetch Users and Projects data.

// web.php

Route::get('/', 'DashboardController@index')->name('dashboard.index');
Route::get('projects', 'DashboardController@getProjects')->name('dashboard.projects');
Route::get('users', 'DashboardController@getUsers')->name('dashboard.users');

DataTables Service Class

For both the UsersDataTable and ProductsDataTable service classes, include the relevant routes we created above.

// UsersDataTable.php

public function html()
{
    return $this->builder()
                ->minifiedAjax( route('dashboard.users') );
}

View

// dashboard.blade.php

@section('content')

   {!! $productsDataTable->table() !!}
   {!! $usersDataTable->table() !!}

@endsection

@push('scripts')

   {!! $productsDataTable->scripts() !!}
   {!! $usersDataTable->scripts() !!}

@endpush
like image 122
Josh D. Avatar answered Mar 15 '23 02:03

Josh D.