I have a model Entry
which has a many-to-many relationship with the model Product
. This relationship has a pivot table (entry_product
) with a valid_to
attribute.
To the database this valid_to
attribute is a timestamp, this is OK. But I would like to format it, before receiving it as a JSON response.
The function responsible for the relationship is the following:
public function products() {
return $this->belongsToMany('Product', 'entry_products')->withPivot(['quantity', 'price', 'valid_to']);
}
Do I have to create a new Model, to support this operation? Is there a way to format all those dates, without looping through the fetched data, before sending it as a JSON response?
You should probably use a model presenter. Model Presenters present the model data in the desired format that we specify.
I recommend you to use laravel-auto-presenter. The documentation is self-explanatory. Please go thru it and if you face any difficulties post it here.
Fortunately, the example given in the documentation uses timestamp.
You can use Laravel5-json package if you want to send response directly.
You can override toJson
method to return the model as you wish. It is lot more independent of external packages and cleaner.