Search code examples
phplaravellaravel-api

Eloquent API Resources - Adding asset link to nested value


I am trying to add an asset link to a nested properties value using Eloquents API resource function:

public function toArray($request)
{
    return [
     'id' => $this->id,
     'title' => $this->title,
     'image' => isset($this->image) ? asset('storage/'.$this->image) : null,
     'properties' => $this->properties,
     'created_at' => (string) $this->created_at,
     'updated_at' => (string) $this->updated_at
   ];
}

The following works fine for the image value, but I am using a nested properties['pdf'] file that I need to add asset('storage/') parameter to so it outputs the full URL.

How am I able to pass isset($this->properties['pdf']) ? asset('storage/'.$this->properties['pdf']) : null into the properties value? I still need the pdf value to return inside the properties value.

Note: There are other values inside properties but they are dynamic based on the data returned.


Solution

  • Probably not the cleanest idea but this worked:

        $properties = $this->properties;
        if(isset($this->properties['pdf']) && $this->properties['pdf'] != null){
          $properties['pdf'] = asset('storage/'.$this->properties['pdf']);
        }
    

    Then I applied $properties to the return.