Eloquent model returns 0 as primary key

- 1 answer

Ad

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"
}
Ad

Answer

Ad

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

Ad
source: stackoverflow.com
Ad