dextersiah1998's avatar

Proper method of uploading image to database

I'm trying to upload my image to my database(MySQL) but it whenever it is saved it in the my table's column it is saved as an array string. Is there a way to remove the ["file.jpg"]whenever i pull the data?

I followed this tutorial for most of the codes Tutorial

Controller

        if($request->hasfile('filename'))
        {
            foreach($request->file('filename') as $image)
            {
                $name = $image->getClientOriginalName();
                $image->move(public_path().'/images/', $name);
                $data[] = $name;
            }
            $project->filename = json_encode($data);
        }

HTML

<input type="file" id="file" name="filename[]" class="custom-file-input">

If im not mistaken the reason it is in an array is because of name="filename[]" and it is converted to a string because of the use of json_encode() . I have tried removing [] but it will give me and error of Undefined variable: data. Anyone able to help? Thanks

0 likes
3 replies
Nakov's avatar

Do you want to upload a single image or multiple images? If you stick to multiple images, than you need to decode your json string once you retrieve it by using json_decode. If you want to keep only one image than you can get rid of the filename[] and use just filename and store the path to the single image as a string value.

dextersiah1998's avatar

@Nakov i want to upload only one picture but when i change it into filename it gives me the error Undefined variable: data

dextersiah1998's avatar
dextersiah1998
OP
Best Answer
Level 1

SOLUTION

if($request->hasfile('filename'))
{
    $imageName = $request->file('filename');
    $name = $imageName->getClientOriginalName();
    $imageName->move(public_path().'/images/', $name);
    $project->filename = $name;
}else{
    dd($request->hasfile('filename'));
}

HTML

<form action="{{ route('project.store') }}" method="POST" enctype="multipart/form-data">
    <input type="file" id="file" name="filename" class="custom-file-input">
</form>

Please or to participate in this conversation.