链接公共目录时,从Laravel中的文件路径中删除“ / public”

时间:2019-08-11 16:49:50

标签: laravel laravel-5

我使用的是5.7.25版本的Laravel。

  1. 我有一个从public/storage/storage/app/public的符号链接。
  2. 我将文件存储在/storage/app/public/place-images目录中。
  3. 我将存储文件的路径保留在表files中,该表保留了所有存储的文件。文件路径为public/images/some_hash.jpg

现在,我制作了一个文件资源,当我从API获取文件时会使用该资源。从api撤消的文件路径等于public/images/some_hash.jpg。但是我需要将其设置为images/some_hash.jpg。但是,在表中,我希望保留与存储文件夹相关的文件的真实路径。毕竟,我可以将文件保存在AWS或其他地方。

据我了解,storage是我的disk的根。 $file->store()方法包括文件路径的public部分。

我最终做了这样的事情:

    // 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
    ];

总有办法避免这种肮脏的骇客吗?我想我缺少明显的东西

1 个答案:

答案 0 :(得分:0)

  1. storage不是磁盘的根。您可以在config\filesystems.php中设置磁盘的根目录。
  2. public中定义的config/filesystems.php磁盘的默认根目录是/storage/app/public,因此只需存储place-images/hash.jpg即可。
  3. 如果要将来自不同磁盘的文件保留在一个表中,只需在该表中添加一个带有磁盘名称的字段即可。
相关问题