Reputation: 3455
Here i am using method chaining on Laravel Eloquent model (User)
with pagination,but after calling method each
pagination stop working.
Is this behaviour expected or i am missing something. there noting mentioned about this on official docs.
User::paginate(10)
->appends(request()->all());
{
"data": [
{
"id": 1,
"email": "[email protected]",
},
{
"id": 2,
"email": "[email protected]",
},
],
"current_page": 1,
"first_page_url": "//localhost/users?page=1",
"last_page": 5,
"last_page_url": "//localhost/users?page=5",
"next_page_url": "//localhost/users?page=2",
"path": "//localhost/users",
"per_page": 10,
"prev_page_url": null,
"total": 50
}
But problem arrives when i call each() method on it
User::paginate(10)
->appends(request()->all())
->each(function ($user) {
$user['someAttribute'] = 'value';
return $user;
})
plain simple result only query records. (Omitted pagination info)
[
{
"id": 1,
"email": "[email protected]",
},
{
"id": 2,
"email": "[email protected]",
},
]
Upvotes: 0
Views: 130
Reputation: 2834
Create an accessor:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getSomeAttributeAttribute()
{
return 'value';
}
}
$users = User::paginate(10)->appends(request()->all());
https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json
Upvotes: 0
Reputation: 868
I don't think you can retrieve the pagination properties after altering the $items
. You'd have to convert the altered data into the LengthAwarePaginator
object manually.
$users = User::paginate(15);
$alteredUsers = $users->getCollection()
->each(function($user) {
$user['someAttribute'] = 'value';
return $user;
});
$newPaginatedUsers = new \Illuminate\Pagination\LengthAwarePaginator(
$alteredUsers,
$users->total(),
$users->perPage(),
$users->currentPage(),
[
'path' => \Request::URL(), // optional
]
)->appends(request()->all());
You can look at the source here and have a better idea of how to build the object.
Upvotes: 1