Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Create Fake Avatar in User Factory

You can create extra methods in your Factory classes. Example: while creating a fake user within UserFactory, you can also add withAvatar() that you would call from the Seeder.

// database/seeders/DatabaseSeeder.php:
User::factory()
->count(10)
->withAvatar() // <-- THIS
->create();
 
// ======================================
 
// database/factories/UserFactory.php:
use Illuminate\Support\Facades\Storage;
 
class UserFactory extends Factory
{
public function withAvatar(): Factory|UserFactory
{
return $this->afterCreating(function (User $user) {
$url = "https://ui-avatars.com/api/?name=" . $user->name;
$contents = Http::get($url)->body();
$name = Str::random(10) . '.png';
Storage::disk('public')->put($name, $contents);
$user->update(['avatar' => $name]);
});
}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses