Reputation: 337
I'm trying to save multiple images in an array to the database, but I'm struggling with that. I've managed to be able to upload the multiple images to the folder just not the database.
My controller
public function store(Request $request)
{
$content = new Content();
$request->validate($this->getRules());
$content->fill($this->getSafeInput($request));
if($request->hasFile('image'))
{
foreach($request->file('image') as $image)
{
$destinationPath = 'content_images/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$content->image = $filename;
}
}
$content->save();
return redirect()->route('content.index');
}
My form
<div class="content-form">
{{ Form::open(array('route' => 'content.store', 'method' => 'post','files'=>'true' )) }}
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" class="form-control" name="title">
</div>
<div class="form-group">
<input type="file" name="image[]" multiple="multiple">
</div>
<input type="submit" class="btn btn-primary" value="Submit"></input>
{{ Form::close() }}
</div>
Upvotes: 3
Views: 15194
Reputation: 11636
You are overriding the value of $content->image
on each image save so finally your $content->image
will have only the name of the last image.
This should work:
if($request->hasFile('image'))
{
$names = [];
foreach($request->file('image') as $image)
{
$destinationPath = 'content_images/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
array_push($names, $filename);
}
$content->image = json_encode($names)
}
Here the image names are initially stored in an array and the array later is saved into db in json
format. so that you can later access them by doing json_decode
and you will have your array of names back!
Upvotes: 8
Reputation: 203
If you want to save the routes of the images separated by ';' you could do something like
public function store(Request $request)
{
$content = new Content();
$request->validate($this->getRules());
$content->fill($this->getSafeInput($request));
$allImages = null;
if($request->hasFile('image'))
{
foreach($request->file('image') as $image)
{
$destinationPath = 'content_images/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$fullPath = $destinationPath . $filename;
$allImages .= $allImages == null ? $fullPath : ';' . $fullPath;
}
$content->image = $allImages;
}
$content->save();
return redirect()->route('content.index');
}
This should make $allImages
a string with each of the paths to the images saved and then save it all in the Content
model.
Upvotes: 0