DEV Community

Cover image for Seed a Laravel Application with Media Files
Yoram Kornatzky
Yoram Kornatzky

Posted on • Edited on • Originally published at yoramkornatzky.com

3

Seed a Laravel Application with Media Files

Laravel-medialibrary is a Laravel package for associating all sorts of files with Eloquent models.

We have an Auction model that uses the library to associate an image with each object,

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Auction extends Model implements HasMedia
{
    use HasFactory;

    use InteractsWithMedia;
}
Enter fullscreen mode Exit fullscreen mode

We wanted to seed an Eloquent model that has associated images using a seeder AuctionSeeder:

class AuctionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Auction::factory()
                    ->count(10)
                    ->create();
     }
}   
Enter fullscreen mode Exit fullscreen mode

running a factory AuctionFactory,

namespace Database\Factories;

use App\Models\Auction;

use Illuminate\Database\Eloquent\Factories\Factory;

class AuctionFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Auction::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => Str::substr($this->faker->words(5, true), 0, 30),
            'description' => $this->faker->text(600),
        ];
    }
Enter fullscreen mode Exit fullscreen mode

To have each generated model associated with an image, we used Unsplash Source to get random images of the required size, by configuring an afterCreating factory callback,

/**
 * Configure the model factory.
 *
 * @return $this
 */
public function configure()
{
    return $this->afterCreating(function (Item $item) {
        $url = 'https://source.unsplash.com/random/1200x800';
        $item
           ->addMediaFromUrl($url)
           ->toMediaCollection('auctions');                
    });
}
Enter fullscreen mode Exit fullscreen mode

One should note that if you plan to generate many images, you need to use the Unsplash API with an API key because of usage limits.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs