这是我的控制器:
public function branchesNearby($lat, $lng)
{
$branches = Branch::all();
//Calculate distance between each branch and client
//Radius of earth is 6371 KM so multiply the result with radius of earth 6371*pi/180
foreach ($branches as $branch){
$branch['distance'] = sqrt(pow(($branch->lat - $lat), 2) + pow(($branch->lng - $lng), 2)) * 108;
}
//Sort by nearest first
$sortedBranches = $branches->sortBy('distance');
return BranchResource::collection($sortedBranches);
}
您可以看到我创建了一个额外的属性来计算用户位置和分支位置之间的距离。然后,我按距离对分支模型进行排序。但是,我得到的api响应是:API response
您可以看到它是一个对象。我不需要键“ 2”,“ 0”和“ 1”。我需要删除此多余的包装,并且我需要它是这样的对象数组:Correct API but without sorting当然,是哪种排序导致它成为对象?我尝试了许多其他方法,其中一种是:
$sortedBranches = $collection->sortBy('distance');
$final = $sortedBranches->values()->toJson();
并将此$ final发送到资源集合。这给了我错误:“在文件api资源中的字符串上调用成员函数first()”。这一定很小,但我确实需要帮助。
正在更新:我以前没有发布过资源,这是这样的:
public function toArray($request)
{
return [
'id' => $this->id,
'shop' => $this->shop->name,
'shop_image' => asset('api/images/' . $this->shop->image_file),
'lat' => $this->lat,
'lng' => $this->lng,
'shop_logo' => asset('api/images/' . $this->shop->logo_file),
'distance' => $this->distance . " KM"
];
如果使用我会得到的错误:
$sortedBranches = $branches->sortBy('distance')->values()->all();
return BranchResource::collection($sortedBranches);
更新3:
如果我不调用资源集合,而只是像这样输出$ sortedBranches:
return response()->json($sortedBranches, 200);
此处,api响应的格式正确,但是数据不正确。它是这样的:$sortedBranches
有没有一种方法可以操纵$ sortedBranches并像BranchResource一样显示输出?
基于我们的故障排除,最终的解决方案应该是:
return BranchResource::collection($sortedBranches)->values()->all();
[将集合传递到BranchResource
类的collect方法时,它将重新创建该集合。 Laravel看到您正在直接从控制器返回一个(集合)对象,并通过将其强制转换为json进行干预(我相信这是默认设置)。如果生成的json没有按照您想要的方式转换,则需要修改此集合。因此,我们需要修改BranchResource::collection()
集合,而不是$sortedBranches
集合。
编辑: