Files
star-erp/app/Modules/Inventory/Controllers/UnitController.php

73 lines
2.2 KiB
PHP
Raw Normal View History

<?php
namespace App\Modules\Inventory\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\Unit;
use App\Modules\Inventory\Models\Product; // Import Product to check for usage
use Illuminate\Http\Request;
class UnitController extends Controller
{
/**
* 將新建立的資源儲存到儲存體中。
*/
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255|unique:units,name',
'code' => 'nullable|string|max:50',
], [
'name.required' => '單位名稱為必填項目',
'name.unique' => '該單位名稱已存在',
'name.max' => '單位名稱不能超過 255 個字元',
'code.max' => '單位代碼不能超過 50 個字元',
]);
Unit::create($validated);
return redirect()->back()->with('success', '單位已建立');
}
/**
* 更新儲存體中的指定資源。
*/
public function update(Request $request, Unit $unit)
{
$validated = $request->validate([
'name' => 'required|string|max:255|unique:units,name,' . $unit->id,
'code' => 'nullable|string|max:50',
], [
'name.required' => '單位名稱為必填項目',
'name.unique' => '該單位名稱已存在',
'name.max' => '單位名稱不能超過 255 個字元',
'code.max' => '單位代碼不能超過 50 個字元',
]);
$unit->update($validated);
return redirect()->back()->with('success', '單位已更新');
}
/**
* 從儲存體中移除指定資源。
*/
public function destroy(Unit $unit)
{
// 檢查單位是否已被任何商品使用
$isUsed = Product::where('base_unit_id', $unit->id)
->orWhere('large_unit_id', $unit->id)
->orWhere('purchase_unit_id', $unit->id)
->exists();
if ($isUsed) {
return redirect()->back()->with('error', '該單位已被商品使用,無法刪除');
}
$unit->delete();
return redirect()->back()->with('success', '單位已刪除');
}
}