I'm struggling to get a relationship value in a LengthAwarePaginator object, I'm trying to get the name of the record creator using the collection transform
method and overriding the created_by
attribute, but I'm getting the whole object and not only the name:
$data = $this->smsTemplateRepository->getAll($page, $pageSize, $filter, $sortBy, $paginate);
$data->transform(function ($item, $key) {
$item['created_by'] = $item->createdBy->name;
return $item;
});
and this is what I'm getting in the frontend
code: "eS5Zx39jXq"
created_at: "2022-05-13T15:55:39.000000Z"
created_by: {id: 2, legacy_user_ref: "bece66c5efe01a4a4fae87650f1072a9", user_type: "employee", client_id: null,…}
id: 5
message: "lIu72gF7S4 {{ worker_name }}2SiQPJAgFrzMw1fzPfqtGSYLY4hgzC1ZOBFaKQGG8T21VSWjmn bye."
name: "fb71e78X07 rQ7ChsUQNr"
sms_legacy_ref: "H6O1BxFBDT"
updated_at: "2022-05-13T15:55:39.000000Z"
updated_by: 2
I'm expecting created_by: 'Name Lastname',
Any ideas, Thanks!!
CodePudding user response:
You can unload the relation once you set the attribute you want
$data = $this->smsTemplateRepository->getAll($page, $pageSize, $filter, $sortBy, $paginate);
$data->transform(function ($item, $key) {
$createdBy = $item->createdBy->name;
$item->unsetRelation('createdBy');
$item->created_by = $createdBy;
return $item;
});