Add dynamically created attributes in ressource

2019-08-22 00:46发布

问题:

I'm working on a project in Laravel where for persistance i'm using a nosql graph based database called neo4j.The thing is that,for a given model,for some reasons the app admin can create new fields in the UI and give the names and validation rules.That means a part from attributes defined in $fillable attributes,new fields are added dynamically.And to manage that,i've created a flexible validation rule for the given model to updated dynamically validation rules by considering new fields,and for persisting them i do $post=Post::forceCreate($data); to ignore the $fillable attributes when creating data,in the database those fields are added successully.The only problem that i have now is that,it's impossible to send them in the PostResource that i defined like this :

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'slug' => $this->slug,
            'title' => $this->title,
            'body' => $this->body,
            'status' => $this->status,
            'image' => $this->image,
            'read_time' => $this->read_time,
            'link' => $this->link,
            'published_at' => $this->published_at,
            'authors' => $this->authors,
            'relatted_spaces' => $this->spaces,
            'tags' => $this->tags()->with('filters')->get(),
        ];
    }
}

This above resource workes fine it can only defined with either known fields or relashionship getters.So how i can i added dynamically added fields in the ressources when i don't even know what will be there names and they don't initialy exist?