amk's avatar
Level 4

Multiple image upload and Insert into multiple row of database...

I want to upload multiple image but I don't want to insert image name in only one row of database. When I upload 4 photos,database must have 4 rows. Anyone can suggest me,how to fix this pls... IDK how to create multiple row of database from controller...

public function store(Request $request)
    {
        $files = $request->file('file');
     foreach ($files as $file) {
         $filename = uniqid() . '_' . $file->getClientOriginalName();
         $file->move(public_path('/images/products'),$filename);
    }

     Media::create([
    
    ??????????
        
    ]);
     return redirect()->route('media.index');

 }

That's from my view..

<form id="target" method="post" action="{{route('media.store')}}" enctype="multipart/form-data">
     {{ csrf_field() }}
    <input type="file" name="file[]" id='fil' multiple> 
</form>
 
   <script>
  $(document).ready(function(){
  $('#fil').change(function() {
  $('#target').submit();
});
});
  </script>
0 likes
6 replies
morteza's avatar
morteza
Best Answer
Level 12

This should do what you want:

public function store(Request $request)
    {
        $files = $request->file('file');
        $filesCollection = collect([]);
     foreach ($files as $file) {
         $path = $request->photo->store('/images/products');
    $filesCollection->push($path);
    }

    $filesCollection->each(function ($path) {
             Media::create([
                         'path' => $path,
                     ]);
        });
     return redirect()->route('media.index');
 }
1 like
amk's avatar
Level 4

It show error like that sir @morteza ... "Call to a member function store() on array";

amk's avatar
Level 4

Got it sir... Thank you so much

imoh's avatar

@morteza i get a call to function store() on array.... please how do i continue

imoh's avatar

yes i did, and its showing the same erro

Please or to participate in this conversation.