File

Laravel File

Fetch the file from url

Directly put into the Storage

To fetch a file from a URL in Laravel, you can use the HTTP facade and its get method.

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

$url = "https://example.com/file.zip";
$contents = file_get_contents($url);
$filename = "file.zip";

Storage::disk('local')->put($filename, $contents);

Transform the fetch url file to the UploadedFile object

use Illuminate\Support\Facades\Storage;
use Illuminate\Http\UploadedFile;

$url = "https://example.com/file.zip";
$contents = file_get_contents($url);
$filename = "file.zip";

$tempFile = tempnam(sys_get_temp_dir(), $filename);
file_put_contents($tempFile, $contents);

$uploadedFile = new UploadedFile($tempFile, $filename, null, null, null, true);

Return the image file with the mime type from the File

use Illuminate\Support\Facades\File;
use Illuminate\Http\Response;

public function showImage($filename)
{
    $path = storage_path("app/public/$filename");
    if (!File::exists($path)) {
        abort(404);
    }
    $file = File::get($path);
    $type = File::mimeType($path);

    return (new Response($file, 200))
              ->header('Content-Type', $type);
}

Return the image file with the mime type from the Storage

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;

public function showImage($filename)
{
    if (!Storage::disk('public')->exists($filename)) {
        abort(404);
    }
    $file = Storage::disk('public')->get($filename);
    $type = Storage::disk('public')->mimeType($filename);

    return (new Response($file, 200))
              ->header('Content-Type', $type);
}