Home >Backend Development >PHP Tutorial >How to Display User Avatars from Laravel Storage in Views?
Background:
Laravel's storage mechanism allows you to store user avatars and other files, but these files are typically located in the /storage folder, which is inaccessible through regular HTTP requests that point to the /public folder.
Solution:
To display user avatars from storage within your views, there are two primary approaches:
1. Creating a Symbolic Link
The recommended approach is to create a symbolic link between the /public/storage folder and the /storage/app/public folder using the following command:
php artisan storage:link
This creates a shortcut that allows you to access storage files as if they were in the /public folder. You can then access the avatar in your view as follows:
<img src="{{ asset('storage/avatars/' . $user->avatar) }}">
2. Using a Custom Route
If you cannot create a symbolic link for any reason, you can define a custom route that reads and serves the image file. Here's an example using a closure route:
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; });
You can then access the avatar in your view using the /storage route:
<img src="{{ route('storage.show', ['filename' => $user->avatar]) }}">
Considerations:
The above is the detailed content of How to Display User Avatars from Laravel Storage in Views?. For more information, please follow other related articles on the PHP Chinese website!