How to route all images from views and css to use IMGIX url in Laravel?

360 Views Asked by At

so I have a laravel project, which is nearly finished and we just transferred all images to the S3 bucket and connected an IMGIX to the S3 buckets so all images are served from the S3 through IMGIX which also enables to do all sorts of customizations on the flight.

However, the images in the CSS are with relative paths, for an example

.bg-image {
   background: url(/storage/icons/icon.svg);
}

And the images in the views, are like this:

<img class="icon" src="{{ asset('storage/icons/icon-white.svg') }}" />

Is there any way I can dynamically add IMGIX url (www.domain.imgix.net) in front of all images on the site (views + CSS) so they all go through the IMGIX?

2

There are 2 best solutions below

1
sherwinski On

According to the laravel docs, you can configure the asset URL host by setting the ASSET_URL variable in your project .env file. For example:

ASSET_URL=https://www.domain.imgix.net

For a more complicated use case, you might want to consider creating a helper method that extends asset and uses the imgix-php client library.

0
Kareem Essawy On

try to edit the routes/web.php

add the following

Route::get('/images/{filename}', function ($filename) {
if (env(    'FILESYSTEM_DRIVER') === 's3') {
    $s3BucketUrl = env('MIX_S3_URL'); // Replace with your S3 bucket URL
    $s3ObjectUrl = $s3BucketUrl . '/images/' . $filename;
    return Redirect::to($s3ObjectUrl);
}
})->where('filename', '.*');