dimanche 11 août 2019

Remove "/public" from file path in Laravel when linking public directory

I use Laravel of 5.7.25 version.

  1. I have a symbolic link from public/storage to /storage/app/public.
  2. I'm storing files in /storage/app/public/place-images directory.
  3. I keep the path of stored file in table files which keeps all stored files. The file path would be public/images/some_hash.jpg.

Now I made a file resource, which is used when I'm getting files from my API. The file path retured from api equals public/images/some_hash.jpg. But instead I need it to be images/some_hash.jpg. However, in the table I prefer to keep real path of the file related to the storage folder. After all, I can keep files in AWS or somewhere else.

As far as I understand storage is the root of my disk. The $file->store() method includes public part of the file path.

I end up doing something like this:

    // This is ImageResource file, Image model has File relation. One Image has one File

    // TODO: Dirty hack
    $path = $this->file->path; // This equals 'public/place-images/hash.jpg'

    // Removing 'public' part
    $charIndex = strpos($path, '/');
    $path = substr($path, $charIndex + 1);

    return [
        'id' => $this->id,
        'original_name' => $this->file->original_name,
         url' => asset('storage/' . $path) // now we have /storage/place-images/some_hash.jpg which is correct
    ];

Is there anyway to avoid this dirty hack? I think I'm missing something obvious



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire