Created
November 3, 2016 11:05
-
-
Save Repox/7784159810681db92b87ca44d5a9464d to your computer and use it in GitHub Desktop.
Laravel 5 Pagination with transform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\User; | |
use Illuminate\Http\Request; | |
class PaginationController extends Controller | |
{ | |
/** | |
* @param Request $request | |
* @return mixed | |
*/ | |
public function index(Request $request) | |
{ | |
// Results per page | |
$limit = 50; | |
// Creates an instance of Illuminate\Pagination\LengthAwarePaginator | |
$users = User::paginate($limit); | |
// getCollection() is a mathod available in Illuminate\Pagination\LengthAwarePaginator | |
// It retrivies the Collection instance the Paginator will iterate over, allowing you to | |
// use Collection methods. transform() modifies the collection itself. | |
$users->getCollection()->transform(function($user, $key) { | |
return [ | |
'name' => $user->name, | |
'email' => $user->email, | |
'custom_attribute' => 'custom value', | |
]; | |
}); | |
return $result; | |
} | |
} |
big thanks @ManojKiranA
I can't get it work, in my vscode, the getCollection()
is undefined method, I tried it too but didn't return anything. Help?
@fahmiegerton try doing without the getCollection()
@fahmiegerton try doing without the getCollection()
Like this?
$users->transform(function($user, $key) {
return [
'name' => $user->name,
'email' => $user->email,
'custom_attribute' => 'custom value',
];
});
Nice broo @ManojKiranA
hope it helps
@ManojKiranAppathurai thank you
thank you dude you save the day @ManojKiranA
Check this out. I am using
tap
helper$users = tap(User::query() ->paginate(100),function($paginatedInstance){ return $paginatedInstance->getCollection()->transform(function ($value) { $value->test = 'test'; return $value; }); });
thanks!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check this out. I am using
tap
helper