Amazon S3 image with Laravel authentication. Sometimes we need to make private our website images, meaning users are not able to view images without logging in. For this purpose, the following code will help us restrict access.
1. First define a route in your route file.
Route::get('aws/images/{path}', [\App\Http\Controllers\TestController::class, 'imageShow'])->where('path', '(.*)')->name('aws_image')->middleware('auth');
2. Create a controller like “TestController” with a method like “imageShow” and call the library.
use App\Library\AwsImage; public function imageShow($path) { return AwsImage::get($path); }
3. In the controller method, we called a library class “AwsImage”. So you can create a class with the following code.
class AwsImage { const DRIVER = 's3'; public static function get($path) { try { $extensions = ['jpg', 'png', 'jpeg', 'gif']; $path_arr = explode('.', $path); $length = count($path_arr); if (!isset($path_arr[$length - 1]) || !in_array($path_arr[$length - 1], $extensions)) { throw new Exception('Invalid image extension'); } $ext = $path_arr[1]; $image = Storage::disk(self::DRIVER)->get($path); if ($image == null) { throw new Exception('Image is not found'); } return response()->make($image, 200, ['content-type' => 'image/' . $ext]); } catch (Exception $e) { return response($e->getMessage(), 404); } } }
4. Everything is ready. Now you can use the following code in your blade file.
<img src="{{ route('aws_image', '$aws_image_path_from_db') }}">