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
Release: 2024-12-26 11:25:09
Original
330 people have browsed it

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
Copy after login

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

http://somedomain.com/storage/image.jpg
Copy after login
Copy after login

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;
});
Copy after login

Access the images using the following path:

http://somedomain.com/storage/image.jpg
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template