Add dynamically created attributes in ressource

时光总嘲笑我的痴心妄想 提交于 2019-12-11 15:14:45

问题


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?

来源:https://stackoverflow.com/questions/56302541/add-dynamically-created-attributes-in-ressource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!