0

I'm trying to store multiple images to the database but it only stores one image. I don't see any errors. I have tried this but it stores images in public folder, I want the images to be stored in database. How can I fix this? any help would be appreciated.

Controller

   if($request->hasFile('files')){
        $files = $request->file('files');
        foreach ($files as $file) {
            $filename = $file->getClientOriginalName();
            $images = $file->store('public/photos');
        }
  }

        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' =>  $images
        ]);

Blade

   <input type="file" name="files[]">
5
  • Add multiple to input, see if that changes things. Try do dd($files); after you set the variable to ese if it actually has multiple items. Commented Dec 12, 2019 at 11:27
  • All images are storing to public/photos folder but not storing all image name in database. Is that your problem? Commented Dec 12, 2019 at 11:27
  • That hasn't changed things @MatthiasS Commented Dec 12, 2019 at 11:29
  • No it only stores one image in database I don't want images to be stored in the project @Jseelb Commented Dec 12, 2019 at 11:30
  • But : $images = $file->store('public/photos'); this is actually storing the file on the disk. What you are storing in the database is only the path to the file. Commented Dec 12, 2019 at 11:34

1 Answer 1

1

I see one issue on your code, you are moving images correctly but storing it in DB outside of loop, which will only store last iteration of loop in DB, you can use this code to store multiple images in DB

if($request->hasFile('files')){

    $store_file = [];
    $files = $request->file('files');
    foreach ($files as $file) {
        $filename = $file->getClientOriginalName();
        $images = $file->store('public/photos');

        $store_file[] = [

            'product_id' => $product->id,
            'filename' =>  $images
        ];
    }

    ProductsPhoto::insert($store_file);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.