EmployeeController.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\employee;
  4. use App\Models\office;
  5. use Illuminate\Http\Request;
  6. use Yajra\DataTables\Facades\DataTables;
  7. use Illuminate\Support\Facades\DB;
  8. class EmployeeController extends Controller
  9. {
  10. public function data(Request $request)
  11. {
  12. $searchValue = $request->search['value']; // User-provided search term
  13. $sql = "
  14. SELECT
  15. employees.name AS employee_name,
  16. employees.email,
  17. employees.position,
  18. offices.name AS office_name,
  19. offices.location AS office_location
  20. FROM
  21. employees
  22. INNER JOIN
  23. offices ON employees.office_id = offices.id
  24. ";
  25. // Apply filtering
  26. if (!empty($searchValue)) {
  27. $sql .= " WHERE employees.name LIKE '%{$searchValue}%'
  28. OR employees.email LIKE '%{$searchValue}%'
  29. OR employees.position LIKE '%{$searchValue}%'
  30. OR offices.name LIKE '%{$searchValue}%'
  31. OR offices.location LIKE '%{$searchValue}%'";
  32. }
  33. // Apply sorting
  34. if(is_array($request->order)) {
  35. $orderColumnIndex = $request->order[0]['column'];
  36. $orderDirection = $request->order[0]['dir'];
  37. $columns = ['employee_name', 'email', 'position', 'office_name', 'office_location'];
  38. $orderColumn = $columns[$orderColumnIndex];
  39. $sql .= " ORDER BY {$orderColumn} {$orderDirection}";
  40. }
  41. // Apply pagination
  42. $start = $request->start;
  43. $length = $request->length;
  44. $sql .= " LIMIT {$start}, {$length}";
  45. // Execute query
  46. $results = DB::select($sql);
  47. $collection = collect($results);
  48. // Total record count for pagination
  49. $totalRecords = DB::select("
  50. SELECT COUNT(*) as count
  51. FROM employees
  52. INNER JOIN offices ON employees.office_id = offices.id
  53. ")[0]->count;
  54. // Total filtered record count
  55. $filteredRecords = empty($searchValue)
  56. ? $totalRecords
  57. : DB::select("
  58. SELECT COUNT(*) AS count
  59. FROM employees
  60. INNER JOIN offices ON employees.office_id = offices.id
  61. WHERE employees.name LIKE '%{$searchValue}%'
  62. OR employees.email LIKE '%{$searchValue}%'
  63. OR employees.position LIKE '%{$searchValue}%'
  64. OR offices.name LIKE '%{$searchValue}%'
  65. OR offices.location LIKE '%{$searchValue}%'"
  66. )[0]->count;
  67. // Return the paginated response
  68. return response()->json([
  69. 'draw' => $request->draw,
  70. 'recordsTotal' => $totalRecords, // Total records without filtering
  71. 'recordsFiltered' => $filteredRecords, // Update if filtered search is applied
  72. 'data' => $results // Current page data
  73. ]);
  74. }
  75. }