Initial commit
This commit is contained in:
41
app/Http/Controllers/Api/ProductController.php
Normal file
41
app/Http/Controllers/Api/ProductController.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use App\Models\Product;
|
||||
use App\Models\Ingredient;
|
||||
|
||||
class ProductController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$products = Product::all();
|
||||
$ingredients = Ingredient::all()->keyBy('id');
|
||||
|
||||
$productsWithIngredients = $products->map(function ($product) use ($ingredients) {
|
||||
$productData = $product->toArray();
|
||||
|
||||
if (isset($productData['products']) && is_array($productData['products'])) {
|
||||
$productData['products'] = collect($productData['products'])->map(function ($item) use ($ingredients) {
|
||||
if (isset($item['data']['ingredients'])) {
|
||||
$item['data']['ingredients'] = collect($item['data']['ingredients'])
|
||||
->map(fn($id) => $ingredients->get($id))
|
||||
->filter()
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
return $item;
|
||||
})->toArray();
|
||||
}
|
||||
|
||||
return $productData;
|
||||
});
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'data' => $productsWithIngredients
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user