Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" } 
like image 598
Alan Avatar asked Dec 25 '15 00:12

Alan


People also ask

What does First () return in Laravel?

It just returns null.

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

What is advantage of eloquent in Laravel?

Laravel Eloquent gives you the freedom to do common database operations without lengthy SQL queries. Models have made insertion, update, deletion, and synchronizing multiple databases very easy. You have to just define database tables and the relation between them and your work is done.

What is eloquent ORM in Laravel example?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database.php .


1 Answers

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

like image 173
lagbox Avatar answered Oct 04 '22 04:10

lagbox