lucassimines's avatar

[Help] Need to add image and text inside a Json DB column

Hello guys, I making some kind of Repeater Field.

I have a DB column named Images, this column actually has some Json image filenames, like:

{"img": ["image1.jpg"],"img":["image2.jpg"]}

Now I'm trying to add a text field (description) to each image inside this column, here are my functions in my Controller, but still no success..

public function update($id, ProjectRequest $request)
    {
        $this_project = $this->project->find($id);
        if ($request->file('images')) {
            $filename = "";
            foreach ($request->images as $key => $img) {
                $file = $img['img'];
                if (empty($file)) {
                    $file_num = $request->uploaded_img[$key];
                    $uploadedFile = $this_project->images['img'][$file_num];
                    $filename .= ',' . $uploadedFile;
                } else {
                    $original_file = $file->getClientOriginalName();
                    $destinationPath = public_path('/images/uploads/');
                    $filename .= ',' . Helpers::safeFilename($original_file);
                    $single_file = Helpers::safeFilename($original_file);
                    $file->move($destinationPath, $single_file);
                    Helpers::createThumbs($single_file);
                }
            }
            $files = trim($filename, ',');
            $files_array = explode(',', $files);

            $request->merge([
                'images' => [
                    'img' => $files_array
                ]
            ]);
            dd($request->all());

            $this_project->update($request->all());

        } 
    }

I'm trying to add the requested image filenames using merge, but if I do that, my text field disappears from the array..

How can I request all values including my images filename and description? Thanks!

0 likes
3 replies
jlrdw's avatar

Use another seperator like

|

But I would consider a rethinking of storing all that in one field.

JMarcher's avatar

Rather than answering your question I'll try to encourage you to change your implementation.

Your implementation violates one of the first principles of database normalization, where "Every row-and-column intersection contains exactly one value from the applicable domain (and nothing else)." -Wikipedia

You may think you don't but storing an array as json in a cell for me kind of does.

In your case I would consider making Image a new Model

lucassimines's avatar

Yea I now it`s not the best way to store, but this Column called Images is inside my model Projects, and I tought it would be easier if I could add it's Images in a repeater, but I'll consider your answers and solve it, thanks!

Please or to participate in this conversation.