結果整理後,應該保留這段正確的 modal:
$product = Product::findOrFail($request->product_id);
$path = $request->file('product_image')->store('product_images', 'public');
// 假設你有個 image_path 欄位儲存圖片路徑
$product->image_path = $path;
$product->save();
return redirect()->back()->with('success', '圖片上傳成功');
}
資料庫顯示:
資料表SQL
CREATE TABLE images
(id
bigint unsigned NOT NULL AUTO_INCREMENT,attachable_type
varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '來源表',attachable_id
varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '來源表ID',path
varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '路徑',filename
varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '檔案名稱',created_at
timestamp NULL DEFAULT NULL,updated_at
timestamp NULL DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
後端
畫面就是自動回到這頁
程式碼
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Http\Controllers\Controller;
use App\Notifications\ProductDelivery;
class ProductController extends Controller
{
public function index(Request $request)
{
$productCount = Product::count();
$dataPerPage = 2;
$productPages = ceil($productCount / $dataPerPage);
$currentPage = isset($request->all()['page']) ? $request->all()['page'] : 1;
$products = Product::orderBy('created_at','desc')
->offset($dataPerPage * ($currentPage - 1))
->limit($dataPerPage)
->get();
return view('admin.products.index',['products' => $products,
'productCount' => $productCount,
'productPages' => $productPages]);
}
public function uploadImage(Request $request)
{
$request->validate([
'product_id' => 'required|integer|exists:products,id',
'product_image' => 'required|image|max:2048',
]);
$product = Product::findOrFail($request->product_id);
$path = $request->file('product_image')->store('product_images', 'public');
// 假設你有個 image_path 欄位儲存圖片路徑
$product->image_path = $path;
$product->save();
return redirect()->back()->with('success', '圖片上傳成功');
}
}
程式碼