Laravel 5 eloquent loading model properties after creation

When creating an eloquent model:

Model::create(['prop1' => 1, 'prop2' => 2]); 

the returned model will only have prop1 and prop2 as properties, what can I do to load all the other properties that I did not insert into the database, because they are optional?

EDIT: Why do I need this? 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 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 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, it will parse all my mutators:

  public function getAddressnoAttribute() { return $this->attributes['fldNumRue']; } 

and raise an error because $this->attributes['fldNumRue'] not defined ErrorException: Undefined index ... Therefore, I need to initialize all the attributes with their default values.

+4
source share
1 answer

You can call the fresh () method on your model. It will reload the model from the database and return it. Keep in mind that it returns a reloaded object - it does not update an existing one. You can also pass an array of relations that need to be reloaded:

 $model = $model->fresh($relations); 

You might consider removing the default values โ€‹โ€‹from the database and your model. This way you do not need to reload the model to get the default values.

You can do this by overriding the $ attributes property in your model and setting the default values โ€‹โ€‹there:

 class MyModel extends Model { protected $attributes = [ 'key' => 'default value' ]; } 
+6
source

All Articles