Crazylife's avatar

Should i create a table to store image path in my database?

Which one is more preferable way to use when storing image path or document path. Should i create a table to store the path or i can just point to disk s3 or local? For example, product images, invoice, document etc.

0 likes
6 replies
jlrdw's avatar

Normally I store the name of image in a table field. Some however choose to store the path and name. Just suggestion.

2 likes
Tippin's avatar

I typically only ever store the file name in the related models table. For example, my messages table, when an attachment message, I only store the file name. However, I have helpers on my Message model that return the full path of the file (I stick in directories, so a message file would be in the parent Thread directory, using the Thread ID.). I also have helpers on the models to return the disk configured for storage.

return Storage::disk($message->getStorageDisk())->response($message->getImagePath());

My helpers:

public function getStorageDisk(): string
{
    return Messenger::getThreadStorage('disk');
}

public function getStorageDirectory(): string
{
    return Messenger::getThreadStorage('directory')."/$this->thread_id";
}

public function getImagePath(): string
{
    return "{$this->getStorageDirectory()}/images/$this->body";
}
2 likes
Crazylife's avatar

@Tippin I see. What if there's multiple attachments? Would it be stored as json?

Tippin's avatar

@Crazylife In my case I do not allow multiple on a single model, however if I did, I would do it the same way, probably editing my helper to return an array back with the full path for each file. My main goal was to make it easy to store, retrieve, and delete files. If a parent thread model is deleted for example, I only need to delete the Thread directory, and all sub files inside will be removed, thus I do not have to loop through files from records to delete each one. Also just helps on my uploads having helpers on models (Thread, Message, User, etc have these directory/path helpers)

//custom service I made
private function upload(UploadedFile $file): string
{
    return $this->fileService
        ->setType(FileService::TYPE_IMAGE)
        ->setDisk($this->getThread()->getStorageDisk())
        ->setDirectory($this->getThread()->getImagesDirectory())
        ->upload($file);
}
2 likes
martinbean's avatar

@crazylife Follow the docs. When you store a file using $request->file('file')->store('path'); it will return the path the file was uploaded to. Store that in your database.

2 likes

Please or to participate in this conversation.