3

I am saving an entity and I would want to get its ID.

$CustomerEntity = CustomerEntity::create([
  'customer_id' => $customer['id'],
  'customer_name' => $customer['name'],
  'address' => $customer['address'],
]);

$CustomerEntity->save();

How do I get the entity ID with that code?

1 Answer 1

9

Use $CustomerEntity->id(); after saving your entity.

$CustomerEntity = CustomerEntity::create([
  'customer_id' => $customer['id'],
  'customer_name' => $customer['name'],
  'address' => $customer['address'],
]);

$CustomerEntity->save();
$id = $CustomerEntity->id();
2
  • This apparently is empty if trying to get it one line below... when halting using a debug breakpoint and then reading it, it is perfectly filled. Jun 7, 2018 at 9:23
  • Just to confirm Florians comment. If you add $entity-save() right after you have created it, then the $entity->id value becomes available. Strange but true. Aug 28, 2020 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.