【发布时间】:2021-11-25 10:38:57
【问题描述】:
请有人帮忙,我是 laravel 的新手,我正在建立一个电子商务网站。我有产品表和图像表。图像表具有 product_id 作为外键。成功创建产品后,我正在尝试存储产品的图像。如何在 ImagesController 存储函数中获取 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 存储功能
$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!');
【问题讨论】:
-
您面临的问题是什么
-
我正在尝试将 product_id 与图像表中的图像一起保存
-
你需要将该变量传递给
create.blade.php -
我收到此错误 - “$product_id is undefined”