【问题标题】:Add parameters to API Resource links in Laravel [duplicate]在 Laravel 中向 API 资源链接添加参数 [重复]
【发布时间】:2018-02-26 11:25:40
【问题描述】:

我的 Laravel 5.5 应用中有很多 API 资源。到目前为止,它们很棒,但我在分页链接中保留 URL 参数时遇到问题。

请看下面的例子 网址:/posts?unreviewed=true

    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 中不包含“reviewed=true”参数,因此第 2 页及以后的页面将返回所有帖子。我需要所有 URL 都包含原始请求中传递的任何参数。

“data”:{...},
“links”:{
   ...
   “next”: “/posts?page=2”
}

我期望的结果是“/posts?unreviewed=true&page=2”

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案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!
    );
    

    【讨论】:

    • 我将此标记为已接受的响应。但是,请注意“附加”必须放在集合部分内,如下所示:return SocialPostResource::collection(SocialPost::with(['images', 'publication.images','brands','products']) -&gt;has('brands') -&gt;paginate($pagination) -&gt;appends(Input::except('page'))); Diego 的响应将其放在外面,这破坏了一些 json 结构。
    猜你喜欢
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2014-12-10
    相关资源
    最近更新 更多