2017-09-18 60 views
0

我的Laravel 5.5應用程序中有許多API資源。到目前爲止,他們都很棒,但我在分頁鏈接中遇到了持久URL參數的問題。將參數添加到Laravel的API資源鏈接

見下 URL的例子:/?的帖子未被研究=真

public function getPosts(Request $request){ 

    /* 
    * Gets a list of posts. 
    * 
    * Options: 
    * - unreviewed: gets posts without revisions (default: false) 
    * 
    */ 

    $pagination = 20; 

    //Check constrains 
    if($request->unreviewed == true){ 
     return SocialPostResource::collection(SocialPost::with(['images', 'publication.images']) 
      ->doesntHave('revisions') 
      ->paginate($pagination)); 
    } 

    return SocialPostResource::collection(SocialPost::with(['images', 'publication.images'])->paginate($pagination)); 

} 

下面的例子僅包括已被修訂的職位。這在第一個查詢中完美工作。問題在於分頁結果不包含URL中的「已審覈= true」參數,因此第2頁及以後的頁面將返回所有帖子。我需要所有URL包含在原始請求中傳遞的所有參數。

「data」:{...}, 
「links」:{ 
    ... 
    「next」: 「/posts?page=2」 
} 

我希望結果是「/帖子?未經審覈=真&頁= 2」

回答

1

我有同樣的問題。事實上,由於你的問題,我發現this similar post,這幫助我找到了解決方案,在我的情況下工作。

請試試這個:

// You must add this Facade in the 'use' section of your file: 
use Illuminate\Support\Facades\Input; 

return SocialPostResource::collection(
    SocialPost::with(['images', 'publication.images']) 
    ->paginate($pagination) 
    ->appends(Input::except('page')) // <- Add this line! 
); 
+0

我標誌着這是公認的響應。但是,請注意,「附加」必須放置在收集部分內,如下所示: 'return SocialPostResource :: collection(SocialPost :: with(['images','publication.images','brands','products ']) - > has('brands') - > paginate($ pagination) - > append(Input :: except('page')));' 迭戈的迴應將它放在外面,這打破了一些json結構。 –

+0

你說得對。更新了答案。謝謝。 – Diego