Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Dan Johnson Avatar asked Mar 14 '23 16:03

Dan Johnson


1 Answers

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.

like image 118
marcanuy Avatar answered Mar 23 '23 23:03

marcanuy