MIF_E31211871/Laravel/app/Http/Controllers/API/ItemController.php

78 lines
2.4 KiB
PHP

<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\Items;
use App\Models\Pickup;
use Illuminate\Http\Request;
class ItemController extends Controller
{
public function index(Request $request)
{
$validated = $request->validate([
'id_pickup' => 'required|string',
]);
$items = Items::with('pickup')->where('kode_pu', $validated['id_pickup'])->get();
// Format data untuk menyertakan biaya dan detail biaya
$formattedItems = $items->map(function ($item) {
return [
'id' => $item->id,
'name' => $item->name,
'price' => $item->price,
'selected' => $item->selected,
'kode_pu' => $item->kode_pu,
'handling_fee' => $item->handling_fee,
'created_at' => $item->created_at,
'updated_at' => $item->updated_at,
'biaya' => $item->pickup->biaya ?? 0, // Include biaya
'detail_biaya' => $item->pickup->detail_biaya ?? 0, // Include detail biaya
];
});
return response()->json($formattedItems);
}
public function update(Request $request)
{
// Validate the incoming request
$validated = $request->validate([
'selected' => 'required|boolean',
'id' => 'required|integer',
'kode_pu' => 'required|string',
'harga' => 'required|integer',
'total_harga' => 'required|integer',
]);
// Retrieve the id and kode_pu from the request body
$id = $validated['id'];
$kodePu = $validated['kode_pu'];
// Find the item by id and kode_pu
$item = Items::where('id', $id)->where('kode_pu', $kodePu)->first();
if (!$item) {
return response()->json(['error' => 'Item not found'], 404);
}
// Update the item with the validated data
$item->update([
'selected' => $validated['selected'],
]);
// Update the harga and total_harga in the Pickup
$pickup = Pickup::where('kode_pu', $kodePu)->first();
if ($pickup) {
$pickup->update([
'biaya' => $validated['harga'],
'detail_biaya' => $validated['total_harga'],
]);
}
return response()->json(['item' => $item, 'pickup' => $pickup]);
}
}