dmytroshved's avatar

Create a Profile immediately after adding a new User through the creation form. Filament 3

Hello

I have a One To One relationship between User & UserProfile models

Inside RegisterController I am creating UserProfile right after creating a user

I am new to Filament, so I am not sure is there is an opprtunity how to achieve that behavior in Filament

User:

    public function profile(): HasOne
    {
        return $this->hasOne(UserProfile::class);
    }

UserProfile:

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

Would be grateful for your help

Best regards

0 likes
7 replies
AddWebContribution's avatar
Level 42

In Filament, you can try this to make sure that UserProfile is always created right after the User

// User.php (Model)
protected static function booted()
{
    static::created(function ($user) {
        $user->profile()->create();
    });
}
1 like
dmytroshved's avatar

@AddWebContribution It works thanks. One more question, can I also send a welcome email from that booted() function? Now, I am sending welcome emails from RegisterController after creating user:

class RegisterController extends Controller
{
    public function __invoke(RegisterRequest $request)
    {
        // Validation & Create User
        $user = User::create([
            ...$request->validated(),
            'password' => Hash::make($request->password),
        ]);

        // Send Welcome Email
        event(new UserRegisteredEvent($user->name, $user->email));

       //...
    }
}
dmytroshved's avatar

@AddWebContribution Can I also delete users profile if user deleted?

I've added:

        static::deleted(function ($user){
            $user->profile()->delete();
        });

into booted() and it works fine

AddWebContribution's avatar

@Dmytro_Shved No, because when you call $user->delete(), Laravel will fire the deleted event after the model has been deleted from the database. At that point, the related profile may not be accessible because the user record no longer exists

Try this instead in booted() because that way you can access all relationships before the model is deleted

static::deleting(function ($user) {
        $user->profile()->delete();
    });

You can also enable cascading deletes via the onDelete('cascade') in your foreign key constraint in the migration.

1 like
dmytroshved's avatar

@AddWebContribution Oh, sure, I have cascading delete in my profiles table:

$table->foreignId('user_id')->constrained('users', 'id')->cascadeOnDelete();

So I don't need to use that code in booted() right?

AddWebContribution's avatar

Yes, just add this line right below where UserProfile is created into booted() method

// Send welcome email
event(new UserRegisteredEvent($user->name, $user->email));
1 like

Please or to participate in this conversation.