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
I got the same issue some days ago and came up with this solution:
First thing you have to do is upload the file to a non-public directory. My app is storing scanned invoices, so I'm going to place them inside storage/app/invoices. The code for uploading the file and generating the url would be:
// This goes inside your controller method handling the POST request.
$path = $request->file('invoice')->store('invoices');
$url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);
The url returned should result in something like http://yourdomain.com/storage/invoices/uniquefilename.jpg
Now you have to create a controller that uses the auth middleware to ensure the user is authenticated. Then, define a method that grabs the file from the private directory and returns it as a file response. That would be:
middleware('auth');
}
public function __invoke($file_path)
{
if (!Storage::disk('local')->exists($file_path)) {
abort(404);
}
$local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;
return response()->file($local_path);
}
}
The last thing is register the route inside your routes/web.php file:
Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])
So there you have it, a pretty reusable snippet for all your projects that deals with private files :)