英文:
append attribute to resurce from resource::make in laravel
问题
I am trying to build a laravel api route to return users data. I got some data stored in txt file. To avoid accessing txt many times, the txt file is read in controller but not in resource.
然而,当我使用UserResource::make($user)
和UserResource::collection($user)
后,我无法给资源的返回分配一些其他属性。
I want to do something like this:
我想要做类似于这样的事情:
$newAttr = $myFileReader->read(abc.txt) //search and return the attr I need
$user_rsc = UserResource::make($user);
$user_rsc['newAttr'] = $newAttr;
return $user_rsc; // the result does not have the newAttr in my case
Is it possible to append attribute after resource::make?
在使用resource::make
之后是否有可能追加属性?
I had try this $user_rsc->additional(['tag' => "haha"]);
before, it does not work in my case.
我之前尝试过$user_rsc->additional(['tag' => "haha"]);
,但在我的情况下没有起作用。
英文:
I am trying to build a laravel api route to return users data. I got some data stored in txt file. To avoid accessing txt many times, the txt file is read in controller but not in resource.
However, after I use UserResource::make($user)
and UserResource::collection($user)
, I cannot assign some other attributes to the return of resource.
I want to do something like this:
$newAttr = $myFileReader->read(abc.txt) //search and return the attr I need
$user_rsc = UserResource::make($user);
$user_rsc['newAttr'] = $newAttr;
return $user_rsc; // the result does not have the newAttr in my case
Is it possible to append attribute after resource::make?
I had try this $user_rsc->additional(['tag' => "haha"]);
before, it does not work in my case.
答案1
得分: 1
我发现从 UserResource::make()
返回的对象是不可变的。我无法通过 additional()
和 with()
方法解决这个问题。最终,我决定暂时采用一个不好的做法来解决它:
以下是解决方案:
$user_rsc = UserResource::make($user)->toArray($request);
$user_rsc['tag'] = $tags;
这个想法是将资源转换为数组,然后附加新属性。
我相当确定这不是一个合适的方法。
英文:
I found that the object returned from UserResource::make() is immutable
. And I cannot solve it by additional()
and with()
. Finally, I decide to use a bad practice to solve it temporarily:
Here is the solution:
$user_rsc = UserResource::make($user)->toArray($request);
$user_rsc['tag'] = $tags;
The idea is to convert the resource to array and append new attribute.
I am pretty sure this is not a proper way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论