我正在尝试在数据库中存储帖子图像,并且正在使用dropzonejs。我能够在存储位置存储图像,这意味着图像可以成功移动存储文件夹。但是当我存储在数据库中时,发生了奇怪的问题。Laravel在数据库中只插入了一些图像吗?
例如,我上传了10张图像,所有文件都移到了存储文件夹中,但是在数据库中仅显示了3条记录?或有时是两个或四个。
该如何解决?
Dropzone配置
Dropzone.options.mDropzoneTwo = {
paramName: "images",
maxFiles: 10,
maxFilesize: 2, // MB
url: '../../media/store',
method: 'POST',
headers: {
"X-CSRF-TOKEN": token,
},
uploadMultiple: true,
accept: function (file, done) {
done();
},
init: function() {
this.on("sending", function(file, xhr, formData){
formData.append("post_type", post.dataset.type);
formData.append("post_id", post.dataset.id);
});
},
success: function () {
console.log(this.files[0].xhr.responseText)
}
};
AdminController
public function storePostMedia(Request $request)
{
// trying to get model by post type, there are several models depending by post types
$table = $request->get("post_type");
$model = getModel($table);
// finding post
$post = $model->find($request->get("post_id"));
$media = new Media;
// store images
foreach ($request->file("images") as $image){
$new_media = $media->storePostImages($image);
$post->media()->save($new_media);
}
}
storePostImages()方法
public function storePostImages($file)
{
// get image - rename - storage to storage folder
$realName = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
$extension = $file->getClientOriginalExtension();
$new_name = str_slug($realName) . "-" . time() . "." . $extension;
$fullPath = \Storage::putFileAs("posts", $file, $new_name);
// save to database
$this->name = $new_name;
$this->path = $fullPath;
return $this;
}
答案 0 :(得分:0)
我为每个记录创建新的模型实例解决了我的问题
foreach ($request->file("images") as $image){
$media = new Media;
$new_media = $media->storePostImages($image);
$post->media()->save($new_media);
}