There are many different ways to get a field value from an entity. For example, a text field:
$entity->get('title')->value;
$entity->get('title')->get(0)->get('value')->getValue();
$entity->get('title')->get(0)->getValue()['value'];
$entity->get('title')->first()->get('value')->getValue();
$entity->get('title')->first()->getValue()['value'];
And so on.
And then, depending on the entity, for the entity title (or name or label), you can sometimes do...
$entity->getName();
What is the best practice? The first expression above (using the "value" property) is most concise -- are there any drawbacks to using it?
Is there any reason to prefer the first() helper instead of get(0)? Why does the first() helper exist? Are there cases when the first value in a field list doesn't have a 0 index?
$entity->field_name->value;
. This always returns 1st value.0
isn't always a key.0
. The key of a list text is stored in the field value.$entity->get('field_name')->getValue()
works well for me, particularly in working with Paragraphs.