Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alex2112's avatar

Convert query builder to eloquent

Hello guys, i have a task where i need to change from query builder to eloquent pagination. This is the code: $draw = (int)$request->input('draw'); $columns = $request->input('columns'); $length = (int)$request->input('length'); $start = (int)$request->input('start'); $skip = $length * $start; $search = $request->input('search'); How will the pagination look like? Thanks :)

0 likes
2 replies
Cristi's avatar

Hello, I am not sure if this will help you but I will leave it here:

$draw = (int)$request->input('draw'); $columns = $request->input('columns'); $length = (int)$request->input('length'); $start = (int)$request->input('start'); $skip = $length * $start; $search = $request->input('search');

//your model name $results = YourModel::select('*');

if (!empty($search['value'])) { $results->where(function($query) use ($search, $columns) { foreach ($columns as $column) { $query->orWhere($column['name'], 'like', '%' . $search['value'] . '%'); } }); }

$totalRecords = $results->count();

if (!empty($request->input('order'))) { $orderColumn = $columns[$request->input('order')[0]['column']]['name']; $orderDirection = $request->input('order')[0]['dir']; $results->orderBy($orderColumn, $orderDirection); }

$results->skip($skip)->take($length);

$filteredRecords = $results->count();

$data = $results->get();

$response = [ 'draw' => $draw, 'recordsTotal' => $totalRecords, 'recordsFiltered' => $filteredRecords, 'data' => $data, ];

return response()->json($response);

1 like

Please or to participate in this conversation.