Reputation: 1318
I have the class Word
that extends Eloquent. I have added two records manually, and they are fetching fine with Word::all()
method. But when I'm trying to create new object and save it, Eloquent inserts empty values into table.
So, here is the model
class Word extends Eloquent {
protected $table = 'words';
public $timestamps = false;
public $word;
public $senseRank = 1;
public $partOfSpeech = "other";
public $language;
public $prefix;
public $postfix;
public $transcription;
public $isPublic = true;
}
Here is the database migration script
Schema::create('words', function($table) {
$table->increments('id');
$table->string('word', 50);
$table->tinyInteger('senseRank');
$table->string('partOfSpeech', 10);
$table->string('language', 5);
$table->string('prefix', 20)->nullable();
$table->string('postfix', 20)->nullable();
$table->string('transcription', 70)->nullable();
$table->boolean('isPublic');
});
And here is the code I'm trying to run
Route::get('create', function()
{
$n = new Word;
$n->word = "hello";
$n->language = "en";
$n->senseRank = 1;
$n->partOfSpeech = "other";
$n->save();
});
And all I get is a new record with correct new id, but all the other fields are empty strings or zeros. How could it be possible?
Upvotes: 2
Views: 2679
Reputation: 1357
Comment out / get rid of class fields you are setting:
// public $word;
// public $senseRank = 1;
// public $partOfSpeech = "other";
// public $language;
Laravel uses magic __get()
and __set()
methods to store fields internally. When you have fields defined, this does not work.
You can use model events to set defaults, add this method to you model:
public static function boot() {
parent::boot();
static::creating(function($object) {
$object->senseRank = 1;
$object->partOfSpeech = "other";
});
}
Upvotes: 1
Reputation: 111829
You need to remove all properties from your model because now Eloquent won't work as it should, your class should look like this:
class Word extends Eloquent {
protected $table = 'words';
public $timestamps = false;
}
If you need default values for some fields, you could add them for example when creating table using default
, for example:
$table->tinyInteger('senseRank')->default(1);
Upvotes: 1