tarikmanoar's avatar

I can't upload multiple images in database

I want to uploads multiple images in my database! Problem is when I submit after selecting multiple images then only one image Uploaded in my database... Here are my View and Controller

Controller

 if ($request->hasFile('image')){
foreach ($request->file('image') as $image){
$fileName = "Photos_".str_random(5).'.'.$image->getClientOriginalExtension();
$image->storeAs('uploads',$fileName);
Image::create([
          'name' => $fileName,
           'album_id' =>random_int(1,5)
 ]);
$this->setSuccessMsg("Image Upload Successful!");
 return redirect()->back();
}
}

VIEW

<div class="form-group row d-flex align-items-center mb-5">
 <label for="image" class="col-lg-3 form-control-label">Image</label>
<div class="col-lg-9">
<input type="file"  name="image[]" id="image" class="form-control" multiple>
</div>
</div>
0 likes
7 replies
Sinnbeck's avatar

Does the images show up on your disk OR is it both that database and you disk that is missing the image?

Nakov's avatar

@tarikmanoar why do you have this:

'album_id' =>random_int(1,5)

Isn't that a relationship with an existing Album from your database? Shouldn't it be like Album with a specific ID..

Maybe that's missing and there is no entry because of that.

Or have you checked your database if there are multiple rows in your images table?

Snapey's avatar

Love how so called programmers don't understand the word or

1 like
jlrdw's avatar

Well like @nakov mentioned if you fix:

random_int(1,5)

That would definitely be a starting point.

And which or does the yes apply to.

Answering the question correctly with as much detail as possible helps us help you.

Also don't forget you have your browser developer tools where you can see what's going on.

tarikmanoar's avatar

Brother, I used 'album_id' =>random_int(1,5) Because I wanna insert a random integer in my album_id. album_id is foregin key!

tarikmanoar's avatar
tarikmanoar
OP
Best Answer
Level 5

Problem is solved by myself ....................

if ($request->hasFile('image')){
foreach ($request->file('image') as $image){
$fileName = "Photos_".str_random(5).'.'.$image->getClientOriginalExtension();
$image->storeAs('uploads',$fileName);
Image::create([
          'name' => $fileName,
           'album_id' =>random_int(1,5)
 ]);
$this->setSuccessMsg("Image Upload Successful!");
 return redirect()->back();
}
}

Here I Return my value inside foreach that's why after one image insert it redirect back......

CODE MUST BE LIKE THIS

if ($request->hasFile('image')){
foreach ($request->file('image') as $image){
        $fileName = "Photos_".str_random(5).'.'.$image->getClientOriginalExtension();
       $image->storeAs('uploads',$fileName);
       Image::create([
               'name' => $fileName,
               'album_id' =>random_int(1,5)
       ]);
       $this->setSuccessMsg("Image Upload Successful!");
}
return redirect()->back();
}

Please or to participate in this conversation.