Improved image insertion in comics

Asked

Viewed 191 times

0

How would be a way to minimize this image insertion code in the database?

//  controller/GaleriasController.php

public function addGaleria {
  $galeria = new Galeria;
  $galeria->descricao = "galeria 1";
  $galeria->img1 = Input::file('img1');
  $name = Input::file('img1')->getClientOriginalName(); 
  Input::file('img1')->move('/arquivos', $name);

  $galeria->img2 = Input::file('img2');
  $name = Input::file('img2')->getClientOriginalName(); 
  Input::file('img2')->move('/arquivos', $name);

  $galeria->img3 = Input::file('img3');
  $name = Input::file('img3')->getClientOriginalName(); 
  Input::file('img3')->move('/arquivos', $name);
  $galeria->save();
}

You are saving the image in the database and directory correctly, only if I had 10 tables with 10 image fields each...

I already tried to create an insertion array only I could not :(

  • are you saving images in the database, or just the image description? Store images in the database in general, is not a good option

  • i saved the image in the directory and the name of the image in the bd, to even thinking of renaming the images with the temporary name that the Laravel creates to avoid images with the same name...

  • "Improvement" sounds better than "Improvement". I think.

1 answer

2


My suggestion to improve is like this:

//  controller/GaleriasController.php

public function addGaleria
{
  $galeria = new Galeria;
  $galeria->descricao = "galeria 1";
  $max = 3;   // quantidade de imagens

  for ($n = 1; $n <= $max; $n++)
  {
    $img = 'img' . $n;
    $galeria->$img = Input::file($img);
    $name = Input::file($img)->getClientOriginalName(); 
    Input::file($img)->move('/arquivos', $name);
  }

  $galeria->save();
}
  • one thing that got me thinking was this: would it be that running the for would not end up inserting only the last looping (img3)... because the save() method runs only after the

  • No. The save should stay after the loop same, and will save at once all the fields of the new Gallery. Exactly as already happens in your code that appears in the question.

  • 1

    I’ll test on my not when I get home.. I hope it works .... and today I still have to insert the filters before that controller... tomorrow put the result J. Bruni

  • Tested and approved...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.