Dan Johnson
Dan Johnson

Reputation: 1482

Getting newly created ID from Eloquent Model Event

I have a model with a non auto-incrementing primary key ID which I have defined in my model.

protected $primaryKey = "ID";

In my AppServiceProvider, I have some model listeners.

Product::created(function ($product){
    dd($product);
});

So if I go to insert a new row:

$NewProduct = new Product;
$NewProduct->ID = 12345;
$NewProduct->Name = "Test";

The event is fired, so the dd gets run in the AppServiceProvider. The ID goes into the database as expected, but the $product array which I'm outputting shows the ID as 0.

Why is the ID showing as 0 when it went into the database as 12345?

Upvotes: 4

Views: 1010

Answers (2)

marcanuy
marcanuy

Reputation: 23972

You should explicitly set the auto increment property as false to make it work. In your model:

protected $primaryKey = "ID";
public $incrementing = false;

Primary Keys

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value. If you wish to use a non-incrementing primary key, you must set the $incrementing property on your model to false.

Upvotes: 4

Adnan
Adnan

Reputation: 8180

I am not sure but did you set incrementing to false in model?

public $incrementing = false;

Upvotes: 3

Related Questions