我有博客文章和多图片上传器两种形式,基本上我想在博客文章表单中使用多图片上传器,但是我需要从博客文章表单中获取 ID,以便每个博客文章都有自己独特的一组图像。我知道您可以使用外键在两个表之间建立链接,但我不确定该怎么做。现在博客文章表单只上传一个文件,所以我想要一种方法将多图像上传器逻辑使用到 PostController 中,然后将其保存到图像表中。非常感谢您的帮助谢谢。
图片控制器
public function store(Request $request)
{
if(!$this->validate($request, [
'id' => 'integer',
'images.*' => 'sometimes|image|nullable|mimes:jpeg,png,jpg,gif,svg,webp|max:25000',
'post_id' => 'required'
])) {
return redirect()->back()->with('errors');
}
if($request->hasfile('images'))
{
foreach($request->file('images') as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('public/image', $fileNameToStore);
$image = new Images;
$image->images = $fileNameToStore;
$image->post_id = $request->post_id;
$image->save();
}
}
return back()->with('Images have been uploaded!');
}
后控制器
public function store(Request $request)
{
// Validate posted form data
$validated = $request->validate([
'id' => 'integer',
'vehicle' => 'required|string',
'h1' => 'required|string',
'page_title' => 'required|string',
'meta_description' => 'required|string',
'image' => 'sometimes|image|nullable|max:5000',
'content' => 'required|string',
'active' => 'integer',
'user_id' => 'required'
]);
子衿沉夜