I'm just starting out my Laravel journey, and have a small project I'm using to consolidate the basics. I'm a bit confused about where/how I deal with calculated fields and Eloquent models. I have a model where I initially put all the properties in the database, but then realised that I didn't actually want the user to input half of them since many are calculated.
So my question, is the model the right place to keep calculated fields (and if so, do I just add them as attributes to the model?) or should I use some other abstraction to separate out the logic from the model?
You can use accessors. In Eloquent it's very simple - you can just add methods named "get[Name]Attribute", where [Name] equals to the name of the calculated attribute.
For example, if you store user's bithday in the database, you can add an accessor to get his age:
protected $dates = ['birthday']; // this tells Eloquent to cast "birthday" attribute into a Carbon instance
public function getAgeAttribute() {
return $this->birthday->age;
}
What if the calculation is expensive and you want to cache it, but not persist it? You obviously don't need your calculated fields in the database. What are the options?