Search code examples
laraveleloquenteloquent-relationship

Eloquent: Create relation if not exist


Subscriptions table: id, client_id, status, valid_until Clients talbe: id, name

Model Client.php:

public function subscription { 
  return $this->hasOne(Subscription::class) 
}

I would like to use $client->subscription->start() to:

  1. If a previous relation already exist: status=1, valid_until \now()+addDays(30)
  2. if relation does not exist create subscription row with above data.

Is it possible? Or do I have to build a static function in subscription.php. ex: Subscription::start($client)

Thanks


Solution

  • I think you need something like https://laravel.com/docs/7.x/eloquent-relationships#default-models with adapt to your requirements.