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" }
It just returns null.
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.
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.
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 .
You can try setting public $incrementing = false;
on your model so eloquent doesn't expect your primary key to be an autoincrement primary key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With