【问题标题】:Creating API Resource Using Laravel使用 Laravel 创建 API 资源
【发布时间】:2018-11-13 13:29:21
【问题描述】:

下面是我的数据,我想用这个创建 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\Component\Debug\Exception\FatalThrowableError (E_ERROR) 在数组上调用成员函数 first()

【问题讨论】:

  • 请在jobpostedservice上使用getJobPosted方法

标签: laravel rest doctrine


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 2020-06-13
    • 2020-03-23
    • 2017-09-06
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多