user3833046 user3833046 - 5 months ago 25
PHP Question

laravel eloquent creating db entry but with null values

I have this problem that laravel eloquent seems creating entry in the database but attributes other than the 'id' are null.

Here's my entity class:


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 save the data to database

$sEnt = new StockEntity("Bank", "BDO", "USD"); //this is just made up data

When I execute the code it is creating entry in the database but with null value columns. I cant post a screenshot but this is how the db looks like:

# id | name | symbol | currency
1 | | |
2 | | |
3 | | |

I spent hours but still can't figure it out. By the way - this is the first time I used laravel and eloquent ORM.

Thanks for your help!


You are not suppose to list your table columns as attributes in your model (i.e. don't declare name, symbol and currency in your model.

And instead of assigning the 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;
  'name' => 'Name',
  'symbol' => 'Symbol',
  'currency' => 'Australian Dollar'