0

I'm seeding responsive images as shown below and it working fine. How can I save the images in webp format regardless of the uploaded format?

My run method

 public function run()
  {
    $seed_imgs_folder = 'http://127.0.0.1:8000/seed_imgs/';

    for ($i = 1; $i <= 4; $i++) {
      $blog = Blog::factory()->create([
        'user_id' => User::all()->random()->id,
        'blog_category_id' => BlogCategory::all()->random()->id
      ]);

      $blog->addMediaFromUrl($seed_imgs_folder . 'blog' . $i . '.jpg')->withResponsiveImages()->toMediaCollection();
    }
  }

My model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Blog extends Model implements HasMedia
{
  use HasFactory;
  use InteractsWithMedia;

  protected $fillable = ['title', 'slug', 'body' . 'user_id', 'blog_category_id'];

  public function user()
  {
    return $this->belongsTo(User::class);
  }

  public function category()
  {
    return $this->belongsTo(BlogCategory::class, 'blog_category_id');
  }
}
Alphy Gacheru
  • 489
  • 1
  • 9
  • 28

1 Answers1

0

It looks like you’ll need to set up your server to run a transformation on each of those images. I don’t know the details of your environment or project. , but this looks like an option. It’s apparently built-in too:

https://www.php.net/manual/en/function.imagewebp.php

Or, there’s an other option. Do the transformation on demand instead of making your server do it up front. I made a service that does exactly this. Prefix an image URL with PicPerf’s domain, and it’ll automatically returned a cached .webp version back (assuming it’s lighter than the original format… and it usually is):

https://picperf.dev

Alex MacArthur
  • 2,220
  • 1
  • 18
  • 22