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

删除“/“公众”;链接公共目录时从Laravel中的文件路径,laravel,laravel-5,Laravel,Laravel 5,我使用5.7.25版本的Laravel 我有一个从public/storage到/storage/app/public的符号链接 我正在/storage/app/public/placeimages目录中存储文件 我将存储文件的路径保存在表files中,该表保存所有存储的文件。文件路径应该是public/images/some\u hash.jpg 现在我制作了一个文件资源,当我从API获取文件时使用它。从api返回的文件路径等于public/images/some_hash.jpg。但是我需要

我使用5.7.25版本的Laravel

  • 我有一个从
    public/storage
    /storage/app/public
    的符号链接
  • 我正在
    /storage/app/public/placeimages
    目录中存储文件
  • 我将存储文件的路径保存在表
    files
    中,该表保存所有存储的文件。文件路径应该是
    public/images/some\u hash.jpg
    现在我制作了一个文件资源,当我从API获取文件时使用它。从api返回的文件路径等于
    public/images/some_hash.jpg
    。但是我需要的是
    images/some_hash.jpg
    。但是,在表中,我更喜欢保留与存储文件夹相关的文件的实际路径。毕竟,我可以在AWS或其他地方保存文件

    据我所知,
    存储
    是我的
    磁盘
    的根目录。
    $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
        ];
    
    有没有办法避免这种肮脏的黑客行为?我想我错过了一些明显的东西

  • 存储
    不是磁盘的根目录。您可以在
    config\filesystems.php
    中设置磁盘的根目录
  • config/filesystems.php
    中定义的
    public
    磁盘的默认根目录是
    /storage/app/public
    ,因此只需存储
    place images/hash.jpg
    而不使用public
  • 如果要将来自不同磁盘的文件保存在一个表中,只需在此表中添加一个具有磁盘名称的字段

  • 在数据库中保存时,为什么不删除public folder呢?因为我认为所有文件路径都应该相对于存储/应用文件夹。比如,一些文件可能不是公共的,另一些可能是公共的。例如,如果我将其他文件存储在storage/app/non-public中该怎么办。有些会有/公开其他不会(在数据库中)嗯,那么tht是您唯一的选择