I have a Eloquent Model and I want to create a customized toArray method...
class Posts extends Model {
public function scopeActives($query)
{
return $query->where('status', '=', '1');
}
public function toCustomJS()
{
$array = parent::ToArray();
$array['location'] = someFunction($this->attributes->location);
return $array;
}
}
//In my controller:
Posts::actives()->get()->toArray(); //this is working
Posts::actives()->get()->toCustomJS(); //Call to undefined method Illuminate\Database\Eloquent\Collection::toCustomJS()
How can I override the toArray method or create another "export" method?
get()actually returns aCollectionobject which contains 0, 1, or many models which you can iterate through so it's no wonder why adding these functions to your model are not working. What you will need to do to get this working is to create your customCollectionclass, override thetoArray()function, and also override the function in your model responsible for building that collection so it can return the customCollectionobject.CustomCollection class
Overriding the newCollection method on your models
And for the models you wish to return
CustomCollectionPlease note this may not be what you are intending. Because a
Collectionis really just an array of models, it's not good to depend on thelocationattribute of a single model. Depending on your use-case, it's something that can change from model to model.It might also be a good idea to drop this method into a trait and then just use that trait in each model you wish to implement this feature in.
Edit:
If you don't want to go through creating a custom
Collectionclass, you can always just do it manually each time...