laravel-nestedset icon indicating copy to clipboard operation
laravel-nestedset copied to clipboard

Use Pagination

Open mitisa opened this issue 6 years ago • 3 comments

Hi dear I want display categories list in a table in my admin panel and need use pagination. when get categories list by Category::get()->toTree() cann't use paginate. How can use paginate? thank you

mitisa avatar Nov 14 '18 22:11 mitisa

The only way to display a tree with pagination is display only root nodes with possibility to expand it and load children via ajax

lazychaser avatar Nov 15 '18 05:11 lazychaser

@programer1010 I have tried this and it works for me

public function index(Request $request)
    {
      $query = Category::query();

        if ($request->has('search')) {
            $query->whereTranslationLike('name', '%' . $request->search . '%');
        }

      return CategoryTreeResource::collection(
        $query->with('children')->withDepth()->paginate(10)
      );
    }

and in model I have create children relation

public function children()
    {
      return $this->hasMany(Category::class, 'parent_id');
    }

and in Resource

public function toArray($request)
   {
        return [
          'id' => $this->id,
         'name' => $this->name,
         'depth' => $this->depth,
         'children' => self::collection($this->whenLoaded('children')),
     ];
   }

That works fine for me. @lazychaser let me know if I wrong or If you do have better suggestions.

Thank you :)

webxteria avatar Jun 13 '19 14:06 webxteria

I guess this won't work efficiently for a large number of records since it fetches the whole dataset, but like in my case where I barely will have more than 100 categories, this works as expected. Please note that I'm using laravel as API service and I only have to return the dataset and total count of records

public function index(Request $request)
    {        
        $limit = $request->has('limit') ? $request->limit : 25;
        $offset = $request->has('page') ? $limit * ($request->page - 1) : 0;

        $resources = PostCategory::withCount('posts')->withDepth()->orderBy('name');
        $count = $resources->count();
        $resources = $resources->get()->toFlatTree();

        $paginated_resources = $resources->skip($offset)->take($limit)->values();

        $data = [
            'count' => $count,
            'data'  => $paginated_resources
        ];

        return $data;
}

lucianobosco avatar Oct 05 '20 23:10 lucianobosco