简体   繁体   中英

Laravel get file from Storage as image/file

In this Laravel 8 project, fromModel method works like a constructor.

class ActiveOrganizationData extends Data
{
    /** @var Image */
    #[Rule(['nullable', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'])]
    public $logo;

    public static function fromModel(Organization $organization): self
    {
        return self::from([
           
            'logo' => $organization->logo,
            
        ]);
    }
}

The $organization-> logo is a string that is a file name coming from the database. I want to cast it as a file/image. How can I do that?

Storage::get() is not working.

Storage::response() is not returning required result.

I got an answer

public static function getLogo(Organization $organization): ?UploadedFile
{
    if (Storage::exists($organization->logo)) {
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file(storage_path().'/app/'.$organization->logo);

        return new UploadedFile(storage_path().'/app/'.$organization->logo, $organization->logo, $mimeType);
    }

    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM