Laravel eloquent creates db record but with null values
I have this problem that laravel eloquent seems to be creating a record in the database, but attributes other than "id" are null.
Here's my entity class:
<?php
class StockEntity extends Eloquent
{
public $name;
public $symbol;
public $currency;
protected $table = 'stocks';
public $timestamps = false;
protected $guarded = array();
protected $fillable = array('name', 'symbol', 'currency');
public function __construct($sName, $sSymbol, $sCurrency)
{
$this->name = $sName;
$this->symbol = $sSymbol;
$this->currency = $sCurrency;
}
}
?>
In my code, I am doing this to store data in the database
$sEnt = new StockEntity("Bank", "BDO", "USD"); //this is just made up data
$sEnt->save();
When I run the code, it creates a record in the database, but with null columns. I can't post a screenshot, but this is what the db looks like:
# id | name | symbol | currency
1 | | |
2 | | |
3 | | |
I've spent hours but still can't figure it out. BTW this is the first time I've used laravel and the eloquent ORM.
Thank you for your help!
source to share
You shouldn't list table columns as attributes in your model (i.e., don't declare name, symbol and currency in your model.
And instead of assigning values ββin your constructor, use ::create()
or ->fill()
.
// This will insert to database and return the object with ID
$stock = StockEntity::create(array(
'name' => 'Name',
'symbol' => 'Symbol',
'currency' => 'Australian Dollar'
));
// This will fill the model object, but not yet saved to database.
$stock = new Stock;
$stock->fill(array(
'name' => 'Name',
'symbol' => 'Symbol',
'currency' => 'Australian Dollar'
));
$stock->save();
source to share
Let Eloquent do its job without trying to force it:
class StockEntity extends Eloquent {
protected $table = 'stocks';
public $timestamps = false;
protected $guarded = array();
protected $fillable = array('name', 'symbol', 'currency');
}
and call with
$sEnt = StockEntity::create(array(
'name' => 'Bank',
'symbol' => 'BDO',
'currency' => 'USD',
));
Learn to use ORM as it is designed to be used
source to share