[英]Laravel 8 - How to get product id in ImagesController store function
請有人幫忙,我是 laravel 的新手,我正在建立一個電子商務網站。 我有產品表和圖像表。 圖像表具有 product_id 作為外鍵。 成功創建產品后,我正在嘗試存儲產品的圖像。 如何在我的 ImagesController 存儲 function 中獲取 product_id 以便可以將其保存在數據庫中?
這是我的圖像表
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('product_id');
$table->string('imagenames');
$table->timestamps();
$table->foreign('product_id')->references('id')->on('products');
});
create.blade.php 用於圖像輸入
<form method="post" action="{{ route('images.post') }}" enctype="multipart/form-data">
@csrf
<div class="control-group">
<input type="hidden" name="product_id" value="{{ $product_id }}"/>
<input type="file" name="filenames[]" class="form-control" multiple/>
</div>
<button type="submit" class="btn btn-success" style="margin-top:10px">Upload</button>
</form>
這是我的 ImageController 商店 function
$this->validate($request, [
'product_id' => 'required|exists:products,id',
'imagenames' => 'required',
'imagenames.*' => 'mimes:png,jpeg,jpg'
]);
$product = Product::find($request->product_id);
if($request->hasfile('imagenames')) {
foreach($request->image('imagenames') as $image) {
$imagename= time() . '_' . $image->getClientOriginalName();
$image->storeAs('public/product_images', $imagename);
$data[] = $imagename;
}
}
$image= new Image();
$image->imagenames= json_encode($data);
$image->save($image);
return back()->with('success', 'Your images were successfully uploaded!');
當您准備 $image 進行存儲時,只需給它 product_id
$image= new Uploadfile();
$image= new File($data);
$image->imagenames= json_encode($data);
$image->product_id= $request->input('product_id');
您應該將product_id
添加到 object
$this->validate($request, [
'product_id' => 'required|exists:products,id',
'imagenames' => 'required',
'imagenames.*' => 'mimes:png,jpeg,jpg'
]);
$product = Product::find($request->product_id);
if($request->hasfile('imagenames')) {
foreach($request->image('imagenames') as $image) {
$imagename= time() . '_' . $image->getClientOriginalName();
$image->storeAs('public/product_images', $imagename);
$data[] = $imagename;
}
}
$image= new Image();
$image->imagenames= json_encode($data);
$image->product_id = $request->product_id ;
$image->save($image);
return back()->with('success', 'Your images were successfully uploaded!');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.