vnc00's avatar
Level 3

Responsive image versions

Hi, I would like to load different background images by device type (mobile, tablet, laptop, desktop/large screen).

Any ideas how to do that in a nice way? I need to deposit different versions of an image (which I edit before upload with photoshop for example for perfect sizing) and show the correct picture by device type - completely dynamically.

My idea:

Schema::create('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug')->unique();
            $table->string('title');
            $table->string('storage_path')->default('/');
            $table->string('extension');
            $table->string('type');
            $table->bigInteger('size')->default(0);
            $table->timestamps();
        });

        Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('file_id');
            $table->string('name');
            $table->enum('device', ['xs', 'sm', 'md', 'lg']);
            $table->timestamps();

            $table->foreign('file_id')
                ->references('id')
                ->on('files')
                ->onDelete('cascade');
        });

Every "file"-object has his own directory in storage/public. So, when I create an article and upload 4 images (for each device type), the directory structure could be:

beautiful-dog/ // file-object
    // the image-objects
    abc.jpg // xs (mobiles)
   defg.jpg // sm (tablets)
    hijk.jpg // md (laptops)
    lmno.jpg // lg (desktops)

Now I can build media-queries like this:

// in Article class
$sizes = ['xs'=>'768', 'sm'=>'992' /*, ...*/];
$queries = $this->file()->images->map(function($item, $key) {
    return '@media screen and (max-width: '.$sizes[$item->device].') { .article-image { background-image: url('.asset($item->slug).'); } }';
});

And print them out in the view:

{{ $queries }}

But... urgh... better solutions?!

0 likes
1 reply

Please or to participate in this conversation.