71 lines
2.1 KiB
PHP
71 lines
2.1 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Http\Controllers;
|
||
|
|
|
||
|
|
use App\Models\Unit;
|
||
|
|
use App\Models\Product; // Import Product to check for usage
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
|
||
|
|
class UnitController extends Controller
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Store a newly created resource in storage.
|
||
|
|
*/
|
||
|
|
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', '單位已建立');
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Update the specified resource in storage.
|
||
|
|
*/
|
||
|
|
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', '單位已更新');
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Remove the specified resource from storage.
|
||
|
|
*/
|
||
|
|
public function destroy(Unit $unit)
|
||
|
|
{
|
||
|
|
// Check if unit is used in any product
|
||
|
|
$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', '單位已刪除');
|
||
|
|
}
|
||
|
|
}
|