I am trying to save several images in the same entry of my projects table, composed of:
id, company_id, project_name, img, files, invoices, date
In my view I have to ask the user to insert the desired images:
<div class="form-group">
<label for="inputClientCompany">Imagen:</label><br>
<input type="file" name='img[]' multiple="" class="form-control">
<br>
<small>Archivos permitidos: jpg,jpeg,png. Tamaño máximo 1mb</small>
</div>
and here I place the save function of my controller:
public function guardar(){
helper(['text','form', 'url']);
$proyectos = new ProyectosModel();
$validacion = $this->validate([
'nombre_proyecto' => 'required|min_length[3]',
'id_empresa' => 'required',
'img' => [
'uploaded[img]',
'mime_in[img,image/jpg,image/png,image/jpeg]',
'max_size[img,1024]'
]]);
$nombreRandom = random_string('numeric', 6);
if (!$validacion){
$session = session();
$session->setFlashdata('mensaje','Por favor, revise la información');
return redirect()->back()->withInput();
}
$nombreRandom = random_string('numeric', 6);
if ($this->request->getFileMultiple('img')) {
foreach($this->request->getFileMultiple('img') as $file)
{
$nuevoNombre = $nombreRandom . '-' . $file->getName();
$file->move('./public/assets/img',$nuevoNombre);
$data = [
'nombre_proyecto'=> $this->request->getVar('nombre_proyecto'),
'id_empresa'=> $this->request->getVar('id_empresa'),
'img' => $nuevoNombre
];
$proyectos->insert($data);
}
}
return $this->response->redirect( site_url('/projectList'));
}
It works "correctly" since it saves and creates the records in the database, the problem is that for each image it creates a new line, and I want all the images to be saved together in the same column, inside an array maybe or something similar, but I can't get it out.
How would it be done? Thank you!! If more information is needed, I will post it.
Change this:
For this:
In this way, it will only generate a single record where the img column will contain the names of the images separated by commas thanks to the implode() function .
The day you need to get that data out of the database again, you will treat it with explode() to return the images to an array.
For example, if a new variable $images contains the value of the img column of a row (result of an SQL query or whatever), you can do this to put them in an array again and then treat them however you like: