Laravel get just data from pagination
Asked Answered
M

3

5

I query the list of users as below:

$users = \App\User::selectRaw('id, "user_name"')->paginate(2);

which returns:

{
    current_page: 1,
    data: [
        {
            id: 2,
            user_name: "user_name"
        },
        {
            id: 3,
            user_name: "user_name"
        }
    ],
    first_page_url: "http://localhost:8000/users?page=1",
    from: 1,
    last_page: 2,
    last_page_url: "http://localhost:8000/users?page=2",
    next_page_url: "http://localhost:8000/users?page=2",
    path: "http://localhost:8000/users",
    per_page: 2,
    prev_page_url: null,
    to: 2,
    total: 3
}

I need to just store the value of users which stored inside data: to a variable, how could I achieve it?

Minority answered 26/11, 2020 at 16:9 Comment(7)
you mean that you need the first 2 users?Stitch
Yes, I mean everything inside data:[] access it separately and store it inside another variable.Minority
Just do $test = $users['data']Stitch
@HafezDivandari I tried but its empty and shows nothing.Minority
@HafezDivandari, I tried this $users->data and it throws error: Undefined property: Illuminate\Pagination\LengthAwarePaginator::$dataMinority
do you have to use paginate? you may $users = \App\User::selectRaw('id, "user_name"')->take(2);Stitch
@HafezDivandari, yes I need to use it and the exact query is not with users, I just simplified my question to reduce the code.Minority
S
9

You may try this:

$users = \App\User::selectRaw('id, "user_name"')->paginate(2);

$data = $users->toArray()['data'];

Or alternatively:

$data = $users->items();
Stitch answered 26/11, 2020 at 16:33 Comment(0)
B
3

You can get the items in the data as

$users = \App\User::selectRaw('id, "user_name"')->paginate(2);


//$users is an instance of `Illuminate\Pagination\LengthAwarePaginator`
//So to get the items

$users->items();
Bracci answered 26/11, 2020 at 16:32 Comment(0)
A
-1

$users = \App\User::selectRaw('id, email')->paginate(2);

$data = $users->getCollection();

Edit: For those who don't know how to convert "Collection" to "Array", the following link from the official laravel documentation will be helpful: https://laravel.com/docs/10.x/collections#method-toarray

PS:

> dd($users->getCollection()->toArray())
array:2 [
  0 => array:2 [
    "id" => 105135
    "email" => "[email protected]"
  ]
  1 => array:2 [
    "id" => 93378
    "email" => "[email protected]"
  ]
]
Audieaudience answered 30/1, 2024 at 15:21 Comment(1)
This returns a collection of User objects, not an array of values.Harangue

© 2022 - 2025 — McMap. All rights reserved.