使用Laravel创建API资源

时间:2018-11-02 07:31:24

标签: laravel rest doctrine

下面是我的数据,我想使用此创建API资源-

array:1 [
  0 => JobPosted {#2635
    -id: 1
    -jobTitle: "Business Development Executive"
    -noOfPosition: 1
    -experience: "2-5"
    -jobLocation: "Mumbai"
    -jobSkill: "Good communication skill, knowledge of Mandarin"
    -jobDescription: "Good communication skill, knowledge of Mandarin"
    -isClosed: false
    -isActive: true
  }
]

我在和laravel一起使用学说。 我的JobResource为

public function toArray($request){
        return [
            'jobTitle' => $this->getJobTitle(),
            'noOfPosition' => $this->getNoOfPosition(),
            'experience' => $this->getExperience(),
            'jobLocation' => $this->getJobLocation(),
            'jobSkills' => $this->getJobSkill(),
            'jobDescription' => $this->getJobDescription()
        ];
    }

和JobResourceCollection为

 public function toArray($request){
            return parent::toArray($request);
        }

而JobController为

public function getJobs(Request $request){
  $jobs = $this->jobPostedService->getJobPosted($limit);
  return response()->json(new JobResourceCollection($jobs), 200);
}

执行此操作后,我收到错误消息

  

Symfony \组件\调试\异常\ FatalThrowableError   (E_ERROR)调用数组上的成员函数first()

1 个答案:

答案 0 :(得分:1)

使用

解决了该问题
 public function getJobs(Request $request){
  $jobs = $this->jobPostedService->getJobPosted($limit);
  return response()->json(new JobResourceCollection(collect($jobs)), 200);
}

代替

public function getJobs(Request $request){
  $jobs = $this->jobPostedService->getJobPosted($limit);
  return response()->json(new JobResourceCollection($jobs), 200);
}