3

I'm getting confused about how to save an image content inside of a database table.

Please see the fourth line of code. I'm sure that this restful method (using POST) is working because getSize() returns the true value.

Also, if I debug what returns the 5th line I get something like the next one:

enter image description here

So, I'm not sure if what am I missing to save this data into the database.

        $personId = Input::get('PersonId');
        $file = Input::file('media');
        $tmppath = $file->getRealPath();
        $content = file_get_contents($tmppath); //$file->getSize();

        // return $content;

        $model = Person::find($personId);
        $model->Photo = $content;
        $model->save();

        $result = array(
            "success" => true,
            "data" => $personId,
            "error" => ""
        );
halfer
  • 19,824
  • 17
  • 99
  • 186
Darf Zon
  • 6,268
  • 20
  • 90
  • 149
  • 2
    Pure curiosity, why not save the location of the image instead of the image data? – Hydra IO Sep 04 '13 at 21:18
  • 1
    You should NOT store binary image data into a database ... store the path/filename of the image in the database like Hydra IO suggested. – djot Sep 04 '13 at 21:20
  • Well, I was thinking in that way you're pointing out me! Do you think is more convenience save it into the server and save the filename instead of save the stream content? – Darf Zon Sep 04 '13 at 21:21
  • Alright, could you show a code about how to save the file in a certain folder of the server? I'm new in this PHP world – Darf Zon Sep 04 '13 at 21:22
  • Here is a really good example: http://www.tizag.com/phpT/fileupload.php – Hydra IO Sep 04 '13 at 21:23

1 Answers1

0

You need to save the file to the server and only store the path in the database.

Write an appropriate method, ideally you can store it in a trait.

private function saveFileToDisk($file, $fileName)
{
    $path = public_path() . '/uploads/';

    return $file->move($path, $fileName . $file->getClientOriginalExtension());
}

An then pass the file input to your method and provide a name for the file:

$model->Photo = $this->saveFileToDisk(Input::file('media'), $model->Name);

Obvisouly you need to validate you input before all this.

Gluten
  • 320
  • 4
  • 12