首页 > 解决方案 > 如何正确地将排序模型从我的控制器发送到 Laravel API 资源集合?

问题描述

这是我的控制器:

    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”。我需要删除这个额外的包装,我需要它是一个像这样的对象数组: 正确的 API 但没有排序 当然,是排序导致它成为一个对象?我尝试了许多其他方法,其中之一是:

$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 一样显示输出?

标签: laravelapiresourceslaravel-resource

解决方案


根据我们的故障排除,得到的解决方案应该是:

return BranchResource::collection($sortedBranches)->values()->all();

当您将集合传递给BranchResource类的 collect 方法时,它会重新创建该集合。Laravel 看到您直接从控制器返回一个(集合)对象,并通过将其转换为 json 进行干预(我相信这是默认设置)。如果生成的 json 没有按照你想要的方式转换,你需要修改这个集合。因此我们需要修改BranchResource::collection()集合,而不是$sortedBranches集合。

编辑:

  • 将 collect 方法修改为 collection;

推荐阅读