To resolve the sorting issue with the status column that exists in the leads table, you need to ensure that the column is properly referenced in your query. Since the status column is part of the leads table, you need to join the leads table with the users table and then sort based on the status column.
Here's how you can modify your code to achieve this:
- Join the
leadstable with theuserstable. - Update the sorting logic to handle the
statuscolumn correctly.
Here's the updated code:
$data = [];
$tableData = [];
$offset = request()->get('start');
$limit = request()->get('length');
$draw = request()->get('draw');
$search = request()->get('search');
$searchValue = $search['value'];
$order = request()->get('order');
$columnOrderIndex = $order[0]['column'];
$columnOrderDirection = $order[0]['dir'];
$columns = request()->get('columns');
$columnData = $columns[$columnOrderIndex]['data'];
// Map the column data to the correct table columns
$columnData = $columnData == 'response' ? 'leads.response' : 'users.' . $columnData;
$users = User::query()
->leftJoin('leads', 'users.id', '=', 'leads.user_id')
->select('users.*', 'leads.response as response');
$totalRecords = $users->count();
if (!empty($searchValue)) {
$users = $users->where(function($query) use ($searchValue) {
$query->where('users.order_id', 'LIKE', '%' . $searchValue . '%')
->orWhere('users.first_name', 'LIKE', '%' . $searchValue . '%')
->orWhere('users.last_name', 'LIKE', '%' . $searchValue . '%')
->orWhere('users.email', 'LIKE', '%' . $searchValue . '%')
->orWhere('leads.response', 'LIKE', '%' . $searchValue . '%');
});
}
if (request()->filled('order_status')) {
$users = $users->where('leads.response', '=', request()->order_status);
}
$totalFilteredRecords = $users->count();
$usersData = $users->orderBy($columnData, $columnOrderDirection)
->offset($offset)
->limit($limit)
->get();
foreach ($usersData as $userData) {
$tableData['order_id'] = $userData['order_id'];
$tableData['first_name'] = $userData['first_name'];
$tableData['last_name'] = $userData['last_name'];
$tableData['email'] = $userData['email'];
$tableData['response'] = $userData->response ?? 'N/A';
$data[] = $tableData;
}
return response()->json([
'draw' => $draw,
'recordsTotal' => $totalRecords,
'recordsFiltered' => $totalFilteredRecords,
'data' => $data,
]);
Explanation:
-
Join the
leadstable: TheleftJoinmethod is used to join theleadstable with theuserstable on theuser_idfield. -
Select the necessary columns: The
selectmethod is used to select columns from both tables. -
Update the column mapping: The
$columnDatavariable is updated to reference the correct table columns. -
Update the search logic: The search logic is updated to include the
responsecolumn from theleadstable. -
Update the sorting logic: The
orderBymethod is updated to sort based on the correct table columns.
This should resolve the sorting issue with the status column in your jQuery DataTable.