Daniel-Pablo's avatar

Get or create a model with a relationship

Hi Buddy, I want to improve this code

public function getOrCreateWalletModel()
    {
		//$this; refers to the USER Model 
        if(!$this->wallet()->exists())
            $this->wallet()->create();

        return $this-wallet;
    }

this is working fine, but I was wondering if there is already any function that makes that for me, in this case, the wallet and user are in a relationship, so I got the USER and make the call to the wallet, on the IF I am requesting to check if the wallet EXIST, If not then Create() after that again it make the call to return the wallet.

So, is there any method already done in Laravel that does this?

thanks in advance, I will mark the best solution as the one that gives a better solution than mine :)

0 likes
2 replies

Please or to participate in this conversation.