#Laravel observer still triggers in seeder even i muted it.

2 messages · Page 1 of 1 (latest)

cosmic veldt
#

Hello. I have a seeder that creates users and also their associated userProfiles. In my UserProfile model, it has an observer that triggers after tue userProfile is created. I want to mute that event for only the seeder but when I do, its still trying to trigger it. Here is my exact code

for the UserProfileObserver

    public function created(UserProfile $userProfile)
    {
        $platform = $userProfile->user->social_identifier['platform'];

        try {
            switch ($platform) {
                case PlatformType::Google->value:
                    $service = new YoutubeService($userProfile->user->social_identifier);
                    break;
    
                case PlatformType::Facebook->value:
                    $service = new FacebookService($userProfile->user->social_identifier);
                    break;
    
                default:
                    return; // Exit early if the platform is not recognized
            }
            SocialPlatform::createFor($userProfile, $service);
        } catch (\Exception $e) {
            Log::error('Error creating social platform: ' . $e->getMessage());
        }
    }

UserSeeder

            $users = User::factory()->count(10)->create();
            $roles = Role::whereNotIn('name', ['admin'])->select('id')->get();
            $flattened = Arr::flatten($roles->toArray());
    
            $users->each(function ($user) use ($faker, $flattened) {
                $completedProfile = false;
                $userProfiles = []; 
    
                foreach ($flattened as $roleId) {
                    $userProfile = $user->userProfiles()->createQuietly([ //ERROR HERE WHEN CREATING
                        'profile_picture' => $faker->imageUrl(),
                        'role_id' => $roleId,
                        'username' => $faker->numerify('user-###'),
                        'is_completed' => $faker->boolean(),
                    ]);
            .....more codes here

i also tried

$userProfile = UserProfile::withoutEvents(function () use ($user, $faker, $roleId) {
    return $user->userProfiles()->create([
        'profile_picture' => $faker->imageUrl(),
        'role_id' => $roleId,
        'username' => $faker->numerify('user-###'),
        'is_completed' => $faker->boolean(),
    ]);
});

But it says #message: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"

thanks in advance.

shrewd fable