Skip to content

Instantly share code, notes, and snippets.

@willchambers99
Created January 30, 2020 16:44
Show Gist options
  • Save willchambers99/be3bf7a69bf957b3a9222a3b83a7703b to your computer and use it in GitHub Desktop.
Save willchambers99/be3bf7a69bf957b3a9222a3b83a7703b to your computer and use it in GitHub Desktop.
How to use Yajra Datatables - https://github.com/yajra/laravel-datatables
<?php
namespace App\Http\Controllers;
use App\Services\SomeApiService;
use Yajra\Datatables\Datatables;
class DatatablesController extends Controller
{
private $api;
public function __construct()
{
$this->api = new SomeApiService();
}
public function index()
{
// EXAMPLE view see what this should look like in seperate gist (yajraUsersTable.blade.php).
return view('datatables.users-table');
}
public function usersTable()
{
$limit = request()->input('length');
$offset = request()->input('start');
$query = request()->input('search')['value'];
// get our users from our API service
$data = $this->api->searchUsers($limit, $offset, $query);
// get our total results
$total = $data->meta->total;
// decode n encode
$users = collect(json_decode(json_encode($data->users, true)));
// create datatables and add 2 custom columns one for view and one for edit these are links
$datatable = Datatables::of($users)
->addColumn('view', function ($users) {
return route('users.view', $users->id);
})
->addColumn('edit', function ($users) {
return route('users.edit.view', $users->id);
})
->setOffset(request()->input('start'))
->setTotalRecords($total);
return $datatable->make(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment