Previewing Pictures Stored in Fake Paths in Laravel

When working with file storage in Laravel, you might need to handle files that are stored with "fake" paths (paths that don't directly correspond to the actual filesystem location). Here's how to preview such images:

Using Laravel's Storage Facade

The most common approach is to use Laravel's storage system with symbolic links:

php
// In your controller
public function previewImage($fakePath)
{
    // Check if file exists in storage
    if (!Storage::exists($fakePath)) {
        abort(404);
    }
    
    // Get the actual file
    $file = Storage::get($fakePath);
    $mimeType = Storage::mimeType($fakePath);
    
    return response($file, 200)
        ->header('Content-Type', $mimeType);
}

Creating a Public Link

For frequently accessed files, create a symbolic link from public storage:

  1. First, configure your filesystem in config/filesystems.php:

php
'disks' => [
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
    // ...
],

  1. Create the symbolic link:

bash
php artisan storage:link

  1. Then store files using:

php
$path = $request->file('image')->store('images', 'public');

  1. Access the image directly via:

html
<img src="{{ asset('storage/'.$path) }}" alt="Preview">

For Non-Public Storage

If the files are in non-public storage (like S3 or local private storage):

php
// Generate a temporary URL (works for S3)
$url = Storage::temporaryUrl(
    $fakePath, now()->addMinutes(5)
);

// Or for local files, create a response
return response()->file(storage_path('app/'.$fakePath));

Using Intervention Image

For more control over image output:

php
use Intervention\Image\Facades\Image;

public function previewImage($fakePath)
{
    $image = Image::make(Storage::get($fakePath));
    
    // Resize or modify if needed
    $image->resize(300, 200);
    
    return $image->response('jpg');
}

To Top