I have successfully deployed my first laravel application on a live server. Everything looks great except the fact that I am unable to display the images that are being uploaded to the
/myproject_src/storage/app/public/myfolder1
folder.
Here is my folder hierarchy on HostGator:
/myproject_src/
Here are all the laravel source files (except the public folder)
/public_html/mydomain.com/
Here goes all my contents of the public directory
I am storing the file path into the database in the following manner:
public/myfolder1/FxEj1V1neYrc7CVUYjlcYZCUf4YnC84Z3cwaMjVX.png
This path is associated with the image that has been uploaded to storage/app/public/myfolder1/ this folder and is generated from store('public/myfolder1');
method of laravel.
What should I do in order to display the images properly in a img tag:
<img src="{{ how to point to the uploaded image here }}">
Well, you can create symbolic link using
php artisan storage:link
and access files using
<img src="{{ asset('public/myfolder1/image.jpg') }}" />
But sometime you can't create symbolic link if you're on shared hosting. You want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example.
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path($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;
});
Now you can access your files like this.
http://example.com/storage/public/myfolder1/image.jpg
<img src="{{ asset('storage/public/myfolder1/image.jpg') }} />
Note: I'd suggest to not store paths in the db for flexibility. Please just store file name and do the following thing in the code.
Route::get('storage/{filename}', function ($filename)
{
// Add folder path here instead of storing in the database.
$path = storage_path('public/myfolder1' . $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;
});
and access it using
http://example.com/storage/image.jpg
Hope that helps :)
The simple answer here is run php artisan storage:link
command manually
first, delete the storage folder inside your public folder
then add this code to the top of the web.php file.
Artisan::call('storage:link');
Hope this will help you.