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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With