samedi 24 septembre 2016

Validate a model has only one type of a relation in Laravel 5

I have a scenario where I am trying to validate that new Contacts can have multiple Email Addresses added to them - however that each Contact can only have one of a certain Email Address Type.

I.e. I want to create Contacts with multiple Email Addresses, but they must have an Email Address which has an Email Address Type of 'work'. They can have zero email addresses or multiple, but always (and only) one work email address.

My models are below. Note, email addresses can be related to objects other than Contact, hence the morphMany.

Contact.php

public function emailaddresses()
{
  return $this->morphMany('EmailAddress', 'emailaddressable');
}

EmailAddress.php

public function emailaddressable()
{
  return $this->morphTo();
}

public function emailaddresstype()
{
  return $this->belongsTo('EmailAddressType', 'email_address_type_id', 'id');
}

EmailAddressType.php

public function emailaddresses()
{
  return $this->hasMany('EmailAddress', 'email_address_type_id', 'id');
}

I am using Laravel 5.1. Any pointers about where to start with this would be great.

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire