Home > Back-end >  Laravel - Modify Fetched Data With Pagination
Laravel - Modify Fetched Data With Pagination

Time:10-05

I want to format some column fetched from database but didn't know how. I use Laravel 8.x. Here's the snippet :

GarageController.php

$q = Garage::with('relative')->paginate(15);
return response()->json($q);

the output

{
  "data": [
    {
      "id": 39819,
      "name": "john",
      "date": "2020-12-20", // i want to format this with date_format()
      "relative": {
        "rid": 912039,
        "rname": "ROV" // and i just want this value instead of all columns
      }
    },
    {
      "id": 38178,
      "name": "danny",
      "date": "2020-12-20", // and this too
      "relative": {
        "rid": 182738,
        "rname": "YIV"
      }
    }
  ],
  "links": {
    .....
  },
  "meta": {
     ....
  }
}

The model, the garage have is belong to relative (relative could have many garage).

public function relative() {
   return $this->belongsTo(Relative::class, 'relative', 'rid');
}

I tried accessor, but it didn't change anything

public function getDateAttributes($value) {
  return date_format(date_create($value), 'd/m/Y');
}

Any help would be appreciated. Thank you.

CodePudding user response:

I think you just need to remove s from the getDateAttributes

From

public function getDateAttributes($value) {
  return date_format(date_create($value), 'd/m/Y');
}

To

public function getDateAttribute($value) {
  return date_format(date_create($value), 'd/m/Y');
}
  • Related