lazychaser / laravel-nestedset

Effective tree structures in Laravel 4-8
3.66k stars 472 forks source link

Use Pagination #323

Open mitisa opened 5 years ago

mitisa commented 5 years ago

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

lazychaser commented 5 years ago

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

webxteria commented 5 years ago

@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 :)

lucianobosco commented 4 years ago

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;
}