Alan
Alan

Reputation: 2639

Eloquent model returns 0 as primary key

I have this migration:

Schema::create('provincias', function (Blueprint $table) {
    $table->string('codigo', 2);
    $table->string('nombre', 50);
    $table->timestamp('creado');
    $table->primary('codigo');
});

This is my model:

class Provincia extends Model
{   
    protected $primaryKey = 'codigo';
    public $timestamps = false;
}

I run the migration and save data like this:

$provincia = new Provincia;
$provincia->codigo = "BA";
$provincia->nombre = "Buenos Aires";
$provincia->save();

The problem is that when I get all and dump:

$provincias = Provincia::all();
return $provincias;

The primary key "codigo" is always 0 even when I check the database table and it has the proper value:

{
    codigo: 0,
    nombre: "Buenos Aires",
    creado: "2015-12-24 21:00:24"
}

Upvotes: 30

Views: 12852

Answers (2)

StrongLucky
StrongLucky

Reputation: 588

You can also set the type of primary key:

protected $keyType = 'string';
public $incrementing = false;

Important note. You should add the second line. $incrementing = false. If you do not this, the key will be 0 after calling save() on your model.

Upvotes: 10

lagbox
lagbox

Reputation: 50491

You can try setting public $incrementing = false; on your model so eloquent doesn't expect your primary key to be an autoincrement primary key.

Upvotes: 106

Related Questions