4

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:

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

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

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!

1
  • Why aren't you using Eloquent's built in generation of properties from your table, and methods like fill()? And you're overriding Eloquent's constructor, stopping it from doing its job Commented Aug 24, 2014 at 21:24

2 Answers 2

2

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;
$stock->fill(array(
  'name' => 'Name',
  'symbol' => 'Symbol',
  'currency' => 'Australian Dollar'
));
$stock->save();
Sign up to request clarification or add additional context in comments.

Comments

1

Let Eloquent do its work 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 using

$sEnt = StockEntity::create(array(
    'name' => 'Bank',
    'symbol' => 'BDO',
    'currency' => 'USD',
));

Learn to use the ORM as it's intended to be used

1 Comment

Mark - I will definitely learn it. Just trying the basic first. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.