I’ve been integrating one of my company’s internal Laravel projects with the excellent spatie/laravel-medialibrary package. To fully test the interface and see how it would look like with data populated, I need to be able to generate the associated media files to the model during the seeding process as well.

To keep it short, I have an Eloquent model called Report which contains the standard fields like name, status, description, author, etc. But the model itself also has associated files which are defined as a collection of PDF of said report.

The model factory in Laravel comes with factory callbacks out of the box, so that’s what I’ve been using to hook into the seeding process and associate media files to the created models. This is how it looks like in its entirety:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php
// the rest of your model factory        
public function configure()
{
    return $this->afterCreating(function (Report $report) {
        foreach (range(1, $this->faker->randomDigitNotNull()) as $key) {
            $name = $this->faker->word() . '.pdf';
            $file = new UploadedFile(database_path('seeders/stubs/sample.pdf'), $name, 'application/pdf', null, true);

            $report->addMedia($file)
                ->preservingOriginal()
                ->usingName($name)
                ->usingFileName($name)
                ->toMediaCollection('documents');
        }
    });
}

Since a report can contain multiple files attached to it, I decided to randomize the number of files associated during the seeding process. For the example above, I put the dummy file inside the database/seeders/stubs directory to make it easier for me to instantiate an instance of Symfony\Component\HttpFoundation\File\UploadedFile. The rest is just a matter of customization, where I use a random word generated by FakerPHP as the filename.

Lastly, you’ll need the preservingOriginal method called, as otherwise, the dummy file will be deleted once it’s added to the model.