我正在嘗試開發一個 Laravel 應用程式,它必須有一個內部 API 來始終獲取資料和前端控制器來使用這個 API 來呈現視圖。此 API 將由移動應用程式使用,因此所有請求都將由 API 處理。
這是我的 API 索引操作,作業正常:
public function index(Request $request)
{
$filters = $request->all();
$query = Place::query()->with('user');
if(!isset($filters['filterType']) || !in_array(Str::lower($filters['filterType']), ['and', 'or']) ){
$filters['filterType'] = 'or';
}
//apply filters
foreach($filters as $filter => $value){
if(Place::hasProperty($filter, app(Place::class)->getTable())){
if($filters['filterType'] == 'and'){
$query->where($filter, $value);
}
else{
$query->orWhere($filter, $value);
}
}
}
//sorting
if(!isset($filters['sortOrder']) || !in_array($filters['sortOrder'], ['asc', 'desc'])){
$sortOrder = 'desc';
}
else{
$sortOrder = $filters['sortOrder'];
}
if(isset($filters['sortBy'])){
$sortBy = $filters['sortBy'];
foreach(explode(',', $sortBy) as $sortField){
if(Place::hasProperty($sortField, app(Place::class)->getTable())){
$query->orderBy($sortField, $sortOrder);
}
}
}
//default pagination
if(!isset($filters['maxResults'])){
$filters['maxResults'] = 5;
}
if(!isset($filters['page'])){
$filters['page'] = 1;
}
//apply pagination
$results = $query->paginate($filters['maxResults'], ['*'], 'page', $filters['page']);
$resultsCollectionResource = PlaceResource::collection($results);
return $resultsCollectionResource;
}
如果我通過郵遞員
Decoded object in frontend:

What I'm doing wrong? Thanks you all.
EDIT
Based on @matiaslauriti response, I changed my API calling to guzzle:
public function index(Request $request)
{
//$places = redirect()->route('api.places.index', ['request' => $request ])->content();
$response = Http::get(env('API_URL').'/places');
$places = $response->object();
return view('places.index', ['places' => $places]);
}
But I still having exactly the same problem. I tested other methods than $response->object(), like collection. But I never get an object that can use $places->links() method in the view.
uj5u.com熱心網友回復:
$places->links()
你傾向于呼叫的這個函式是 Laravel 分頁器類的成員,$places應該是這個類的實體來支持這個函式
如果你想繼續你擁有的這個實作,并支持 Laravel 分頁功能,你應該創建一個 Laravel lengthawarepaginator實體并手動創建分頁器實體。
根據它的引數,這可能看起來像這樣:
在您的前端控制器中添加:
$paginatedPlaces = new LengthAwarePaginator($places->data, $places->meta->total, $places->meta->per_page)
然后傳遞$paginatedPlaces給你的觀點
我建議的第二個選項是,不要使用->links()函式,只需簡單地從回應中列印出鏈接屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/389882.html
標籤:php laravel api laravel-8 laravel-api
