Framework: makeVisible() after pagination change structure of toJson() (or toArray())

Created on 22 Nov 2016  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.3
  • PHP Version: 7.0

Description:

after _paginate()_ method it normally return's json object, with "_total_", "_per_page_" and other params and "_data_" key, collecting Users Collection

after _paginate()->makeVisible('field')_ result contain's only Users Collection

Steps To Reproduce:

Fresh Laravel 5.3 installation

Route::get('/', function () {
    return \App\User::where('id', '>', '1')->paginate(5);
});

it return's normal pagination json object

{
    "total": 23,
    "per_page": 2,
    "....other_fields": "valuesssss",
    "data": [
        {
            "id": 4,
            "name": "Susie Leuschke I",
            "email": "[email protected]"
        },
        {
            "id": 5,
            "name": "Pearl Schneider II",
            "email": "[email protected]"
        }
    ]
}

after cast _makeVisible()_ method

Route::get('/', function () {
    return \App\User::where('id', '>', '1')->paginate(5)->makeVisible('password');
});

only Users Collection

[
    {
        "id": 4,
        "name": "Susie Leuschke I",
        "email": "[email protected]",
        "password": "blabla"
    },
    {
        "id": 5,
        "name": "Pearl Schneider II",
        "email": "[email protected]",
        "password": "blabla"
    }
]

i use stupid _where_ condition for example, because it's return Builder object, which has no method to make fields visible

Most helpful comment

That's because makevisible() returns a Collection not a LengthAwarePaginator instance, so this is an intended behaviour, if you want to alter the collection inside the paginator but still have access to the paginator instance you can use getCollection, alter it, and put it back into setCollection().

Closing this issue since it's not a bug, but feel free to open a PR with a proposed change if you have any.

All 3 comments

That's because makevisible() returns a Collection not a LengthAwarePaginator instance, so this is an intended behaviour, if you want to alter the collection inside the paginator but still have access to the paginator instance you can use getCollection, alter it, and put it back into setCollection().

Closing this issue since it's not a bug, but feel free to open a PR with a proposed change if you have any.

@themsaid Thanks a lot!

I think a small example would be in place, since setCollection() is not well documented...

    $query = Task::where( 'tasktype', 'Eat' );
    $resource = $query->paginate( 15 );
    $resource->setCollection( $resource->getCollection()->makeVisible( 'created_at' ) );

Note, setCollection() is only available for instances of AbstractPaginator

Was this page helpful?
0 / 5 - 0 ratings