I am building an API with Laravel for VueJS frontend SPA.
I need to accept and return dates as 'd-m-Y', not as 'Y-m-d' as it's stored in DB. Data mutator is working ok and I managed to save it properly with given date, but when I run:
$active = Announcement::where('group_id', $this->user->group_id)->where('dateTo', '>=', Carbon::today())->get();
return response()->json($active);
I am getting pure DB data, instead of getting it formatted.
For example I have dateTo
field which needs to be formatted :
public function getDateToAttribute($value)
{
$date = Carbon::createFromFormat('Y-m-d', $value);
return $date->format('d-m-Y');
}
What should I do?
As @Jared said, accessors/mutators only exist when called by your application. So, in collection returned as JSON, no accessor/mutator exist. Make a loop to call all your needed accessor/mutator is waaay too fat, but Laravel come with a built-in solution
In your model Announcement.php
, you just have to specifies the accessors/mutators that will always be appended on your requests.
protected $appends = array('dateTo');
With this solution, each request will contain a dateTo parameter, formated as you like.
greets !
PS : You can make the $appends
array change depending on your request, so all your request returning JSON will send the dateTo
parameters, but the other won't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With