When creating an eloquent model:
Model::create(['prop1' => 1, 'prop2' => 2]);
the returned model will only have prop1
& prop2
as properties, what can I do to eager load all others properties that I haven't inserted in database because they are optional ?
EDIT: Why do I need this ? to rename my database fields:
database
CREATE TABLE `tblCustomer` (
`pkCustomerID` INT(11) NOT NULL AUTO_INCREMENT,
`baccount` VARCHAR(400) NULL DEFAULT NULL,
`fldName` VARCHAR(400) NULL DEFAULT NULL,
`fldNumRue` VARCHAR(10) NULL DEFAULT NULL,
....
PRIMARY KEY (`pkCustomerID`)
);
customer model
<?php namespace App\Models;
/**
* Class Customer
* @package App\Models
* @property int code
* @property string name
* @property string addressno
*/
class Customer extends Model
{
protected $table = 'tblCustomer';
protected $primaryKey = 'pkCustomerID';
public $timestamps = false;
/**
* The model's attributes.
* This is needed as all `visible fields` are mutators, so on insert
* if a field is omitted, the mutator won't find it and raise an error.
* @var array
*/
protected $attributes = [
'baccount' => null,
'fldName' => null,
'fldNumRue' => null,
];
/**
* The accessors to append to the model's array form.
* @var array
*/
protected $appends = [
'id',
'code',
'name',
'addressno'
];
public function __construct(array $attributes = [])
{
// show ONLY mutators
$this->setVisible($this->appends);
parent::__construct($attributes);
}
public function setAddressnoAttribute($value)
{
$this->attributes['fldNumRue'] = $value;
return $this;
}
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
}
The problem is that when Laravel converts everything to JSON, he will parse all my mutators:
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
and raise an error as $this->attributes['fldNumRue']
is not defined ErrorException: Undefined index... So I need a way to initialize all attributes with their default values.