I'm trying to do store post images at database and I'm using dropzonejs. I'ma able to store images at storage, I mean images successfully move storage folder. But when I store at database, weird problem happening.. Laravel insert just some of images at database ?
For example, I had uploaded 10 images, all files moved storage folder but in database only three records show up ? or sometimes two or four..
How do I fix this ?
Dropzone configuration
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() method
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;
}
I solved my problem with creating new model instance for each record
foreach ($request->file("images") as $image){
$media = new Media;
$new_media = $media->storePostImages($image);
$post->media()->save($new_media);
}