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 the pictures are accessible to unauthenticated users as well by going to Inspect Element of chrome and then changing the user IDs. Kindly help out me...
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
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
class ImageController extends Controller {
public function __construct()
{
$this->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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With