How to check if a multi value reference field already has a value I need to check if a multi-valued reference field (referencing other nodes) in a node has a specific value already present to avoid duplicates.

here is the code:

$portFolioNode =  \Drupal\node\Entity\Node::load( $form_state-&gt;getValues()['portfolios'] );

//now save location id to reference field.
//$portFolioNode-&gt;field_portfolio_locations[] = ['target_id' =&gt;  $form_state-&gt;getValues()['location_nid']  ];

// how can I check if location_nid is present already?
$portFolioNode-&gt;field_portfolio_locations[]  = $form_state-&gt;getValues()['location_nid'] ;

$portFolioNode-&gt;save();


Any help will be appreciated greatly. Thanks!
You can check the field's values before saving:

// Id to check if exists.
$query_id = 123;

// Create array of existing ids in field.
$existing_ids = array_column($entity-&gt;my_entity_reference_field-&gt;getValue(), 'target_id');

// Check if the $query_id is not in the existing ids.
if (!in_array($query_id, $existing_ids)) {
  // In here means your $query_id doesn't already exist in the field's values.
}



Your code updated:

// Load portfolio node id and new location id from form_state.
$portfolioId = $form_state-&gt;getValue('portfolios');
$newLocationId = $form_state-&gt;getValue('location_nid');
if (!empty($portfolioId) &amp;&amp; !empty($newLocationId)) {
  // Load portfolio node.
  $portfolioNode = \Drupal::entityTypeManager()
    -&gt;getStorage('node')
    -&gt;load($portfolioId);

  // Get existing location ids from portfolio node.
  $existingPortfolioLocationIds = array_column($portfolioNode-&gt;field_portfolio_locations-&gt;getValue(), 'target_id');
  // If new location id is not an existing location id, add to node and save.
  if (!in_array($newLocationId, $existingPortfolioLocationIds)) {
    $portfolioNode-&gt;field_portfolio_locations[] = $newLocationId;
    $portfolioNode-&gt;save();
  }
}