Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CReflex's avatar

Laravel auto create relation entry with default data

I'm trying to make a wallet system in my Laravel application.

Letme explain my database structure first I have the default users table.

And each user hasOne wallet, like this:

// User model
public function wallet()
{
    return $this->hasOne(Wallet::class);
}

Now, what I want to achieve is whenever I query wallet like:

$user->wallet

I want if the user doesn't have wallet a new wallet should be created automatically with default values.

I couldn't find a way to do this in a organized and efficient manner.

Please suggest a way.

Thank you so much for reading :)

0 likes
4 replies
CReflex's avatar

@MichalOravec This is exactly what I wanted, but there's a slight problem. I'm doing it like

// User model
public function wallet()
  {
        return $this->morphOne(Wallet::class, 'walletable')->withDefault(function ($wallet, $user) {
            $wallet->balance = 0;
            $wallet->withdrawable_balance = 0;
            $user->wallet()->save($wallet);
        });
  }

It works, but whenever I'm trying to eager load wallet for user like: User::with('wallet')->find(1) it creates another wallet entry on the database doesn't matter if it already exists. Check this image: https://prnt.sc/LNCKpAXFtkAo

I think the problem is, while eager loading the withDefault closure always getting executed. :/

MichalOravec's avatar

@CReflex exists property should work, so just add a if statement there like:

if (! $wallet->exists) {
    $user->wallet()->save($wallet);
}

Please or to participate in this conversation.