I am new to Laravel and trying to store private images so that only authenticated users can access them. Firstly I stored images in Public/UserImages folder. But here all th
Following is how I solved the problem of storing images in Laravel 5 such that only authenticated users can view the images. People who are not authenticated will be directed to a login page. My server is a Ubuntu/Apache2 server.
Create the directory /var/www/YOURWEBSITE/app/Assets/Images
Add route to app/Http/routes.php.
Route::get('/images/{file}','ImageController@getImage');
Create a controller app/Http/Controllers/ImageController.php
middleware('auth');
}
public function getImage($filename) {
$path = '/var/www/YOURWEBSITE/app/Assets/Images/'.$filename;
$type = "image/jpeg";
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($path));
readfile($path);
}
}
In your view you have img tags which have:
src="{{ url('/images/test.jpg') }}"
This of course assumes test.jpg is a file in /var/www/YOURWEBSITE/app/Assets/Images/
You can of course add more logic such as not hardcoding the path of the images, etc. This is just a simple example to enforce authentication. Note the use of middleware('auth') in the controller constructor.