For many websites, it’s common to display images that are uploaded by users. Often the images are available to all other visitors of the website, but sometimes you want to protect the image files. For example, you want people to first create an account before they are allowed to view certain content. How can this be achieved in Laravel?
Create an image folder
First, you create a folder to which users may upload their files. You can place this folder in the ‘storage’ directory, or another directory in the root of the project. In this case, I call this folder ‘uploaded_images’. A .htaccess file is added to this directory to prevent people to access the uploaded files via the url. The .htaccess file has the following content:
order deny, allow deny from all
Create a route
Now the images cannot be accessed directly, but how do we make the images available for authorized users?
In this example, I want to use the following url to display the image: www.example.com/uploads/filename.jpg
Therefore, I first create an ‘ImageController’ and a ‘view-image’ middleware. Next, add the following line of code to the routes file:
Route::get('uploads/{slug}', ['uses' => 'ImageController@show','middleware' => 'view-image']);
Then, open the ImageController and add the following code:
public function show($slug) { $storagePath = 'uploaded_images/'. $slug; return Image::make($storagePath)->response(); }
Protect the route with middleware
The last step is to write your logic for the view-image middleware that is protecting the route. In a simple setup, where you only want visitors to be loggedin to your website, the following code may be used:
if (Auth::id()) { return $next($request); } return Response::make(‘Forbidden’,403);
Of course, you may extend this code and create more sophisticated logic whenever you need.
This is all you need to protect your images for unauthorized people, while authorized users can access them via www.example.com/uploads/filename.jpg.