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:
// 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:
First, configure your filesystem in
config/filesystems.php
:
'disks' => [ 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ], // ... ],
Create the symbolic link:
php artisan storage:link
Then store files using:
$path = $request->file('image')->store('images', 'public');
Access the image directly via:
<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):
// 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:
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'); }