Since your Datatables is serverside you can specify the record length by iDisplayLength option. Just add the following line in your options, like after processing: true,
'iDisplayLength': 10,
Now to make it work instead of getting all the rows and passing the collection you just construct the query and pass it to Datatables. Yes it accepts query without get() and it automatically decides which rows to get based on iDisplayLength and the position pointer which Datatables holds client-side. Also it would be nice to mention select so you don't go select *. So you do something like this:
$users = User::select(['user_id', 'name', 'email', 'phone_number', 'btn_login');
return Datatables::of($users)
...
Datatables pagination is on by default so this should work.
Also if you want to fetch relations you need to manually join the tables and select specific data. And this is a must because loading relations through eloquent models affects you performance even worse. Lets assume you have a contacts table and the contacts are stored in that table, with user_id to make it belong to the user, but a user may happen not to have a contact so it should be a left join instead of inner join. Here is the query to make it work. You need to first import DB though.
use IlluminateSupportFacadesDB;
$query = DB::table('users as u')
->leftJoin('contacts as c', 'u.user_id', '=', 'c.user_id')
->select(['u.user_id', 'u.name', 'c.email', 'c.phone_number', 'u.btn_login');
return Datatables::of($query)
...
Also now for the table search and order to work you need to pass the correct name of column with their table selector as name to datatables, so the columns options will look like this:
columns: [
{data: 'user_id', name: 'u.user_id'},
{data: 'name', name: 'u.name'},
{data: 'email', name: 'e.email'},
{
data: 'phone_number',
name: 'c.phone_number',
defaultContent: "---"
},
{data: 'btn_login', name: 'u.btn_login'}
]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…