Home >Backend Development >PHP Tutorial >How Can I Access Storage Images in Laravel Views?

How Can I Access Storage Images in Laravel Views?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 11:25:09324browse

How Can I Access Storage Images in Laravel Views?

Accessing Storage Images in Laravel Views

When working with uploaded images stored in Laravel storage, displaying them in views can present a challenge. Since the server routes requests to /public, accessing images stored in /storage requires a solution.

Symbolic Link

The recommended approach is to create a symbolic link between /public/storage and /storage/app/public. This command is available in Laravel versions 5.3 and later:

php artisan storage:link

This creates a symlink allowing you to access files in /storage/app/public using paths like:

http://somedomain.com/storage/image.jpg

Closure Route

If symbolic link creation is not an option, you can define a closure route to read and serve the images:

Route::get('storage/{filename}', function ($filename) {
    $path = storage_path('public/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

Access the images using the following path:

http://somedomain.com/storage/image.jpg

Warning

Manually serving files incurs a performance penalty compared to server-side handling. However, this approach is useful for protected files or environments where symbolic links cannot be created.

The above is the detailed content of How Can I Access Storage Images in Laravel Views?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn