Amazon S3 image with laravel authentication

laravel image authentication

Amazon S3 image with laravel authentication. Sometimes we need to make private of our website images that means user is not able to view image without login. For this purposes, the following code will help us to do the restriction.

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 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)
            $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') }} ">

Leave a Comment