Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - accessor doesn't work when collection returned as JSON

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?

like image 453
Marek Urbanowicz Avatar asked Dec 18 '22 14:12

Marek Urbanowicz


1 Answers

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.

like image 61
Jiedara Avatar answered Mar 14 '23 18:03

Jiedara