Laravel: how to retrieve a model’s primary key after saving it

Asked

Viewed 222 times

1

would like to know if it is possible to recover the ID of a model at the time it is saved in the bank. I am using the following Eloquent method:

$modelo = Modelo::create(['ATT1' => 'valor1', 'ATT2'=>'valor2']);

The model is saved, but the primary key is not returned in the $model variable. I’m doing it right or there’s something wrong?

  • What is the primary key column called? It is varchar(2) auto-increment?

1 answer

1

I usually do as follows, using your example would look like this:

$modelo = Modelo::create(['ATT1' => 'valor1', 'ATT2'=>'valor2']);

return $modelo->id;

if the primary key for name id would look like this.

  • I have tried to do it this way, but it returns null. Primary key is varchar(2) and I am not sure if it is auto increment. This may be affecting?

  • I’m pretty sure you do, take the test that I believe is exactly that.

  • CREATE TABLE Modelo ( id int(10) unsigned NOT NULL AUTO_INCREMENT,), would be so as I would with my Primary key.

  • In my case, I do not know if this change in the bank will be possible :( but I will try with another model then. Thank you!

  • You can try a CAST on your model, Ex: protected $Casts = [ 'id' => 'integer' ];

  • And what would I do $Casts? I saw that I have a $keyType property in the default int model. I tried switching to string but it didn’t solve my problem.

  • For me to understand your problem better, your Primary key will be a varchar , correct ? so it’s not being automatically incremented , the right thing would be before you do create $model = Template::create(['ATT1' => 'value1', 'ATT2'=>'value2']); , it would be interesting to generate a code to insert into the Primary key, so you could return her value.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.