ProductController.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Egg;
  4. use App\Models\Location;
  5. use App\Models\Node;
  6. use App\Models\Product;
  7. use Illuminate\Database\Eloquent\Builder;
  8. use Illuminate\Http\JsonResponse;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Collection;
  11. class ProductController extends Controller
  12. {
  13. /**
  14. * @description get product locations based on selected egg
  15. * @param Request $request
  16. * @param Egg $egg
  17. * @return Collection|JsonResponse
  18. */
  19. public function getNodesBasedOnEgg(Request $request, Egg $egg)
  20. {
  21. if (is_null($egg->id)) return response()->json('egg id is required', '400');
  22. #get products that include this egg
  23. $products = Product::query()->with('nodes')->whereHas('eggs', function (Builder $builder) use ($egg) {
  24. $builder->where('id', '=', $egg->id);
  25. })->get();
  26. $nodes = collect();
  27. #filter unique nodes
  28. $products->each(function (Product $product) use ($nodes) {
  29. $product->nodes->each(function (Node $node) use ($nodes) {
  30. if (!$nodes->contains('id', $node->id) && !$node->disabled) {
  31. $nodes->add($node);
  32. }
  33. });
  34. });
  35. return $nodes;
  36. }
  37. /**
  38. * @description get product locations based on selected egg
  39. * @param Request $request
  40. * @param Egg $egg
  41. * @return Collection|JsonResponse
  42. */
  43. public function getLocationsBasedOnEgg(Request $request, Egg $egg)
  44. {
  45. $nodes = $this->getNodesBasedOnEgg($request, $egg);
  46. $locations = collect();
  47. //locations
  48. $nodes->each(function (Node $node) use ($nodes, $locations) {
  49. /** @var Location $location */
  50. $location = $node->location;
  51. if (!$locations->contains('id' , $location->id)){
  52. $nodeIds = $nodes->map(function ($node){
  53. return $node->id;
  54. });
  55. $location->nodes = $location->nodes()
  56. ->whereIn('id' , $nodeIds)
  57. ->get();
  58. $locations->add($location);
  59. }
  60. });
  61. return $locations;
  62. }
  63. /**
  64. * @param Node $node
  65. * @return Collection|JsonResponse
  66. */
  67. public function getProductsBasedOnNode(Node $node)
  68. {
  69. if (is_null($node->id)) return response()->json('node id is required', '400');
  70. return Product::query()->whereHas('nodes', function (Builder $builder) use ($node) {
  71. $builder->where('id', '=', $node->id);
  72. })->get();
  73. }
  74. }