在Laravel中,将属性追加到resource::make中的资源中。

huangapple go评论47阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月22日 13:33:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76303269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定