public function search($input) { $query = Module::query(); $columns = Schema::getColumnListing('modules'); $attributes = array(); foreach ($columns as $attribute) { if (isset($input[$attribute]) and !empty($input[$attribute])) { $query->where($attribute, $input[$attribute]); $attributes[$attribute] = $input[$attribute]; } else { $attributes[$attribute] = null; } } return [$query->get(), $attributes]; }
public function getModules(Request $input) { $query = \App\Models\Module::query(); if ($input->has('id')) { $id = $input->get('id'); if (is_array($id)) { $query->whereIn('modules.id', $id); } else { $query->where('modules.id', $id); } } if ($input->has('category_id')) { $id = $input->get('category_id'); $query->leftJoin('modules_categories', 'modules.id', '=', 'modules_categories.module_id'); if (is_array($id)) { $query->whereIn('modules_categories.category_id', $id); } else { $query->where('modules_categories.category_id', $id); } } $fullModules = $query->select('modules.*')->with('categories')->get(); $moduleIDs = $fullModules->lists('id'); $responseImages = []; /* SELECT mp.module_id, SUM(mp.amount * p.price) FROM homestead.module_plants as mp LEFT JOIN homestead.plants as p on mp.plant_id = p.id GROUP BY mp.module_id ; */ $dbPricesQuery = \DB::table('module_plants AS mp')->leftJoin('plants AS p', 'mp.plant_id', '=', 'p.id')->select(['mp.module_id', \DB::raw('SUM(mp.amount * p.price) AS price')])->whereIn('mp.module_id', $moduleIDs)->groupBy('mp.module_id'); $dbPrices = $dbPricesQuery->get(); $prices = []; foreach ($dbPrices as $price) { $prices[$price->module_id] = $price->price; } /** @var Module $module */ foreach ($fullModules as $module) { $responseImages[$module->id] = ['id' => $module->id, 'top_image' => $module->top_image_hash, 'front_image' => $module->front_image_hash, 'mature_front_image' => $module->mature_front_image_hash, 'price' => array_get($prices, $module->id, 0), 'height' => $module->height, 'width' => $module->width, 'categories' => $module->categories->lists('slug', 'id')]; } return response(json_encode($responseImages, JSON_FORCE_OBJECT), 200, ['Content-Type' => 'application/json']); }