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:
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.