Marek Urbanowicz
Marek Urbanowicz

Reputation: 13664

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?

Upvotes: 5

Views: 3775

Answers (3)

Jiedara
Jiedara

Reputation: 526

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.

Upvotes: 14

Parithiban
Parithiban

Reputation: 1666

Try This

    $active = Announcement::where('group_id', $this->user->group_id)->where('dateTo', '>=', Carbon::today())->get();
    foreach($active as $activeRecords){
       print_r($activeRecords->dateTo);
    }

Attribute

public function getDateToAttribute($value)
{
    return Carbon::parse($value)->format('d-m-Y');
}

Upvotes: 0

Jared Rolt
Jared Rolt

Reputation: 591

Laravel will run the accessors when you convert the model to an array or json.

So I would update your code to:

$active = Announcement::where('group_id', $this->user->group_id)->where('dateTo', '>=', Carbon::today())->get();

return response()->json($active->toArray());

Upvotes: 0

Related Questions