1

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?

6

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. – Florian Müller Jun 7 '18 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. – Alan Gentle Aug 28 '20 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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