Also, as a side note, whenever I do something like
$activities = Activity::paginate(10);
dd($activities);
my browser (firefox) crashes.
Any ideas?
If anyone is interested I found the solution here (although I had to modify it slightly)
https://laracasts.com/forum/?p=1715-filtering-pagination-result/0
I also had the same problem when first I fetched paginated items from DB and later I needed to do some further filtering. After many tries I came up with:
$activities= Activity::paginate(10);
$filteredActivities=$activities->filter(function($activity){
return $activity->filter();
}
$array=[];
foreach($filteredActivities as $item)
{
$array[]=$item;
}
$activities->setItems($array); //filtered activities with pagination
I adapted the solution from: http://www.jarrodtoh.com/laravel-collection-pagination/
$activities = Activity::all(); $filteredActivities = $activities->filter(function($activity) { // Code in here });
// Paginate $perPage = 10; // Item per page (change if needed) $currentPage = (Input::get('page') == 0 ? 1 : Input::get('page')) -1; $pagedData = $filteredActivities ->slice($currentPage * $perPage, $perPage)->all(); $collection= Paginator::make($pagedData, count($filteredActivities), $perPage);
The example in the first post was mostly correct. Just don't reassign the value of paginator instance, this is already done for you when you are iterating an underlying collection. Below is the working example from my application:
$posts = Post::published()->orderBy('published_at', 'desc')->simplePaginate(10);
$posts->map(function ($item, $key) {
$item->content = TextHelper::truncate($item->content, 300, [
'exact' => false,
'html' => true,
]);
return $item;
});
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community