Search code examples
phplaravelvite

How to Load Background Images from the Public Directory in CSS with Vite in Laravel?


I'm working on a Laravel project and using Vite for asset management. I have a situation where the logo image is stored in the resources folder, while the demo images are kept in the public folder. I want to set a background image in a CSS file located in resources, but the image itself is in the public folder.

How can I configure the CSS file to correctly load the background image from the public folder when using Vite?


Solution

  • To load a background image from the public folder in a CSS file managed by Vite:

    Hardcode the Public Path: Use the direct URL in your CSS:

    .example-class {
        background-image: url('/path/to/image/in/public/folder/image.jpg');
    }
    

    Use Blade asset Helper: Reference the image in your Blade template:

    <style>
        .example-class {
            background-image: url('{{ asset('path/to/image/in/public/folder/image.jpg') }}');
        }
    </style>
    

    Move Images to resources Folder: Place images in resources/images and reference them with Vite:

    .example-class {
        background-image: url('/images/image.jpg');
    }
    

    --- OR ---

    S3 Image Reference in CSS Use the Storage Facade in Blade: In your Blade template, dynamically generate the

    S3 URL:

    <style>
        .example-class {
            background-image: url('{{ Storage::url('path/to/image/on/s3/image.jpg') }}');
        }
    </style>
    

    Configure Storage Disk: Make sure your filesystems.php is configured correctly for S3:

    'disks' => [
        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],
    ],
    

    Use this approach for S3-hosted images to ensure the URL is generated correctly and is accessible.