Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add some data in laravel paginate

As the tittle said, Here is my Controller

$book = Data::where('userId','1')->paginate(3);

return response()->json($book);

And get the json data like this:

data:[{id: 1, userId: 1, vendorId: 1, name: "Alfreda Berge PhD", phone: "1-850-813-5950 x96169",…},…]
from:1
last_page:2
next_page_url: "http:/localhost/XX/public/user/book/list/1?page=2"
perpage:4
prev_page_url:null
to:4
total:5
// if I want to add a new column and value here ,what should I do? 

I tried to do this :

$book = Data::where('userId','1')->paginate(3);
$book->printWord = 'Hellow!';
return response()->json($book);

But, It seem will remove the column printWord. Any idea?

like image 392
Fan Avatar asked Dec 08 '16 07:12

Fan


People also ask

How can I get pagination data in Laravel?

Laravel's paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database records with zero configuration. By default, the HTML generated by the paginator is compatible with the Tailwind CSS framework; however, Bootstrap pagination support is also available.

How does pagination work Laravel?

Pagination works by selecting a specific chunk of results from the database to display to the user. The total number of results is calculated and then split between pages depending on how many results you want to return on a page.


2 Answers

You can create collection with custom data manually and use merge() helper:

$book = Data::where('userId','1')->paginate(3);

$custom = collect(['my_data' => 'My custom data here']);

$data = $custom->merge($book);

return response()->json($data);

Just checked, it works just fine.

like image 141
Alexey Mezenin Avatar answered Oct 04 '22 00:10

Alexey Mezenin


If you use the Illuminate\Pagination\LengthAwarePaginator class "manually", there's the option of extending it and overriding the toArray method:

return new class(
    $collection,
    $count,
    $limit,
    $page,
    // https://github.com/laravel/framework/blob/6.x/src/Illuminate/Pagination/LengthAwarePaginator.php#L40
    // values here will become properties of the object
    [
        'seed' => $seed
    ]
) extends LengthAwarePaginator {
    public function toArray()
    {
        $data = parent::toArray();
        // place whatever you want to send here
        $data['seed'] = $this->seed;
        return $data;
    }
};

Result

current_page    1
data    []
first_page_url  "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
from    null
last_page   1
last_page_url   "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
next_page_url   null
path    "/finder"
per_page    20
prev_page_url   null
to  null
total   0
seed    0.2 // <-- our custom prop

There's some extra work involved with instantiating LengthAwarePaginator yourself, but it gets the job done.

like image 22
BrunoRB Avatar answered Oct 04 '22 00:10

BrunoRB