I am using spatie / medialibrary
to handle the associations to media files to my models and it's a great power-ful package.
If you are using the package and looking to associate fake images to your models via medialibrary via database seeder for testing purposes. Here is how you can do it.
I have a product model to which I need to associate product images, Here is how my Product model looks like
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
class Product extends Model implements Searchable, HasMedia
{
use HasMediaTrait;
public function registerMediaCollections()
{
$this->addMediaConversion('thumb')
->width(200)
->height(200)
->sharpen(10);
}
}
and here is how I am associating fake images via faker package to the product model in DatabaeSeeder
class.
<?php
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$products = factory('App\Product', 25)->create();
$faker = Faker::create();
$imageUrl = $faker->imageUrl(640,480, null, false);
foreach($products as $product){
$gift->addMediaFromUrl($imageUrl)->toMediaCollection('images');
}
}
}
Comments