+1 vote
by
Greetings!

I'm studying Laravel 5.4 to create an online store.
At the moment, my first app is an online store.

The product should have a photo gallery.
Photos are uploaded to the specified folder.
Question:
How to save file names in the database in one column?

Thank you in advance!
Form
<div class="form-group">
<label for="imageInput">File input</label>
<input required="" data-preview="#preview" name="input_img[]" type="file" id="imageInput" multiple>
</div>
Controller:
$paths = [];
foreach($request->input_img as $imag) {

$image = $imag->getClientOriginalName();

$actual_name = pathinfo($image,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($image, PATHINFO_EXTENSION);

$i = 1;
while(file_exists('images/products/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$image = $actual_name.".".$extension;
$i++;
}

$imag->move(Config::get('app.upload_path') . 'images/products', $image);
$dir=public_path('images/products/thumbnails/');
if( ! \File::isDirectory($dir) ) {
\File::makeDirectory($dir, 493, true);
}


}

$product->image = $paths;

$product->save();
Error
(1/1) ErrorException
Array to string conversion

in AdminProductController.php line 95
at HandleExceptions->handleError(8, 'Array to string conversion
by
Code.
by
Amondullo What is it like to code in Notpad?
by
Stanislav Pochepko ,line 95: $product->image = $paths;
by
Stanislav Pochepko Thank you, thank you! You have helped me a lot.
by
Amondullo , with my hands.
by
Amondullo Well, serialize it in JSON and save it.
$product->images = json_encode($paths);
by
What line of code do you have line 95 on?
by
$product->image = $paths; -this string does not save to the database. $paths is an array that contains the names of all photos
by
To formalize the code has already been asked, and I would suggest to update Lara and then already dance somewhere
by
JhaoDa how?

1 Answer

0 votes
by
 
Best answer
Make a one-to-many link to the Image object in the database.
You will bind images to the product.
And in the image object itself store ID, originalName, path, product_id.
Then you won't have a mess in your head and you'll figure out how it works, and the scheme is more transparent.
In the controller, after saving an image, create an object for it and save it to the database with the necessary links
...