【发布时间】:2020-06-10 17:03:58
【问题描述】:
我有两种形式的博客文章和多图片上传器,基本上我想在博客文章表单中使用多图片上传器,但是我需要从博客文章表单中获取 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'
]);
// Create slug from title
$validated['slug'] = Str::slug($validated['vehicle'], '-');
$validated['active'] = isset($request->active[0]) ? 1 : 0;
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/image', $fileNameToStore);
}else {
$fileNameToStore = null;
}
// Create and save post with validated data
$post = new Post;
$post->id = $request->input('id');
$post->vehicle = $request->input('vehicle');
$post->slug = $request->input('slug');
$post->h1 = $request->input('h1');
$post->page_title = $request->input('page_title');
$post->meta_description = $request->input('meta_description');
$post->image = $fileNameToStore;
$post->content = $request->input('content');
$post->active = $validated['active'];
$post->user_id = $request->input('user_id');
$post->slug = $validated['slug'];
$post->save();
// Redirect the user to the created post with a success notification
return redirect(route('admin.posts.show', $post))->with('notification', 'Post created!');
}
【问题讨论】: