FilterController.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\FilterRequest;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Schema;
  6. class FilterController extends Controller
  7. {
  8. const DB_TABLES = [
  9. 'orders' => 'orders_view',
  10. 'product_sku' => 'mafs_view',
  11. 'products' => 'products',
  12. 'reclamations' => 'reclamations_view',
  13. 'maf_order' => 'maf_orders_view',
  14. 'import' => 'imports',
  15. ];
  16. public function getFilters(FilterRequest $request)
  17. {
  18. $table = $request->validated('table');
  19. $column = $request->validated('column');
  20. if(!array_key_exists($table, self::DB_TABLES)) {
  21. abort(400, 'Table not found');
  22. }
  23. $gp = session('gp_' . $table);
  24. $dbTable = self::DB_TABLES[$table];
  25. if (Schema::hasColumn($dbTable, $column)) {
  26. $q = DB::table($dbTable)->select($column)->distinct();
  27. if(!in_array($table, ['reclamations', 'import'])) {
  28. $q->where('year' , year());
  29. }
  30. if (Schema::hasColumn($dbTable, 'deleted_at')) {
  31. $q->whereNull('deleted_at');
  32. }
  33. if(isset($gp['filters']) && is_array($gp['filters']) && count($gp['filters'])) {
  34. foreach ($gp['filters'] as $colName => $vals) {
  35. $q->where(function ($query) use ($gp, $colName, $vals) {
  36. foreach (explode('||', $vals) as $val) {
  37. $query->orWhere($colName, '=', $val);
  38. }
  39. });
  40. }
  41. }
  42. // dd($q->toRawSql());
  43. $result = $q->orderBy($column)->get()->pluck($column)->toArray();
  44. } else {
  45. $result = [];
  46. }
  47. return response()->json($result, 200, [], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
  48. }
  49. }