Laravel and algolia, ignore array if null -


i have code:

public function tosearchablearray() {     $data = $this->toarray();     $data['_geoloc'] = $this->_geoloc->toarray();     $data['address'] = $this->address->toarray();     return $data; } 

however $data['entities'] null therefore throwing me error:

 [symfony\component\debug\exception\fatalthrowableerror]   call member function toarray() on null 

is there way by-pass that?

you need check elements if exist , not null before call methods on them, this:

public function tosearchablearray() {     $data = $this->toarray();     $data['_geoloc'] = !empty($this->_geoloc) ? $this->_geoloc->toarray() : null;     $data['address'] = !empty($this->address) ? $this->address->toarray() : '';     return $data; 

}

also $this->toarray(); convert model instance array relations. need load them like: $this->load('_geoloc', 'address'); , call $data = $this->toarray();


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -