获取产品id以存储相应的附件



我现在有add attachment按钮在产品列表页面上的每个产品。单击按钮后,将继续添加附件表单。如何从产品表中获取当前产品ID,以便将附件数据存储到附件表中?

Route::post('/store/{product}', 'AttachmentController@store')->name('attachment.store');

产品模型

public function attachment()
{
return $this->hasMany(Attachment::class, 'product_id', 'id');
}
<<p>附件模型/strong>
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}

控制器

public function create()
{        
return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {        

$data['product_id'] = $product->id;
$data = $request->validate([
'file' => 'required',
'file.*' => 'mimes:csv,xlsx,pdf,docx',
]);
$attachmentData = [];   
if($request->hasFile('file'))
{
foreach($request->file('file') as $file) {
$path = public_path('storage/attachments/'.$request->product_id);
$fileName = time().'-'.$file->getClientOriginalName();
$file->move($path, $fileName);
$attachmentData[] = $fileName;
}
$data['file'] = json_encode($attachmentData);
}
$attachment = Attachment::create($data);
return redirect()->route('product.index')->with('success','Attachment added successfully');
}
<<p>叶片视图/strong>
<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
@csrf
<h3><b>Add Attachment</b></h3>
<input type="submit" class="btn btn-primary mr-2" value="Save">
<div class="row">
<h4 class="card-title">General</h4>
<input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Attachment </label>
<div class="input-group-append">
<label for="attachment" class="btn btn-info">Upload</label>
<input id="attachment" type="file" name="file[]" multiple required>
</div>
</div> 
</div>
</form>

你必须像下面这样使用form动作

<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

相关内容

  • 没有找到相关文章

最新更新