Home > Backend Development > PHP Tutorial > How to Access Stored Images in Laravel Views for Optimal Performance?

How to Access Stored Images in Laravel Views for Optimal Performance?

Linda Hamilton
Release: 2024-12-09 03:22:11
Original
715 people have browsed it

How to Access Stored Images in Laravel Views for Optimal Performance?

Accessing Images Uploaded in Laravel Storage for View Rendering

In Laravel applications, user avatars or other media assets may be stored within the storage directory. To access and display these images in a view, you have several options:

1. Create a Symbolic Link

From Laravel 5.3 onwards, the artisan storage:link command creates a symbolic link from public/storage to storage/app/public. This allows you to access files in the latter directory using the former path:

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

2. Use a Custom Route for File Service

If creating a symbolic link is not feasible, you can create a custom route to read and serve 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

With this route, you can access files using the following path:

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

3. Use Intervention Image Library (Optional)

If using the Intervention Image Library, you can leverage its response() method:

Route::get('storage/{filename}', function ($filename) {
    return Image::make(storage_path('public/' . $filename))->response();
});
Copy after login

Important Note:

Manually serving files may incur a performance penalty compared to letting the HTTP server handle it directly. Therefore, consider symbolic links as the preferred method for optimal performance.

The above is the detailed content of How to Access Stored Images in Laravel Views for Optimal Performance?. 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