我需要将多个对象发送到api资源。所以我要在数组内返回多个Object。一切正常,但不显示任何分页元数据。例如Current_page,next_page网址等。
#navbar {
overflow: hidden;
background: rgba(139, 139, 157, 0);
display: flex;
justify-content: flex-end;
border-bottom: 5px solid white;
padding-bottom: 20px;
padding-top: 20px;
position: fixed;
top: 0;
width: 100%;
}
.content {
padding: 60px 16px 16px 16px;
color: #ddd;
background-color: #FFF
}
我的资源
return [
'across_city' => ServiceProviderCollection::collection($across_city),
'near_by' => ServiceProviderCollection::collection($near_by)
];
我的控制器: 在这里,我有两种类型的用户。用户和整个城市的用户。我将它们作为数组发送到ServiceProviderCollection。
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ServiceProviderCollection extends Resource
{
public function toArray($request)
{
return
[
'name'=>$this->forename,
'rating'=>$this->rating,
'price'=>$this->price,
'distance'=>round($this->distances,1),
];
}
}
我想要带有分页的Json Data。
$user_city = $userObj->location->city;
$locationObj = Location::whereNotIn('id', $blockeduser)->where('city',$user_city)->first();
$across_city = $locationObj->users()->simplePaginate(20);
$near_by = User::join('locations as l', 'users.location_id', '=', 'l.id')
->select('users.*', DB::raw('(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $coordinates['longitude'] . ')) + sin(radians(' . $coordinates['latitude'] . ')) * sin(radians(`lat`)))) as distances'))
->having('distances', '<', $max_distance)
->orderBy('distances', 'ASC')
->where('role_id',2)
->whereNotIn('id', $blockeduser)
->simplePaginate(20);
return [
'across_city' => ServiceProviderCollection::collection($across_city),
'near_by' => ServiceProviderCollection::collection($near_by)
];
答案 0 :(得分:1)
我不知道ServiceProviderCollection
的目的是什么。如果它创建了常规集合,则会有better way to do so。
要能够对简单的集合进行分页,您需要将此辅助函数添加到基础中:
function paginateCollection($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
return new \Illuminate\Pagination\LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
使用此功能,您可以制作
return [
'across_city' => paginateCollection(collect($across_city), 20),
'near_by' => paginateCollection(collect($near_by), 20)
];
您是否已生成相应的资源集合?
像这样:php artisan make:resource Cities --collection
如果是,则可以返回paginated resource collection