laravellaravel-9laravel-resource

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. 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.


Solution

  • 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.