Skip to main content
Quick Tip

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]);
});
}

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Laravel 13 Eloquent: Expert Level

41 lessons
1 h 34 min

NativePHP v3: Create Mobile Apps with Laravel

10 lessons
1 h 02 min

Laravel AI SDK: 6 Practical Examples

9 lessons
1 h 02 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.