Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filament Trilist Laravel Package

beholdr/filament-trilist

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require beholdr/filament-trilist
    

    For Filament 5.x, ensure version ^1.1.x is used.

  2. Publish Views (Optional):

    php artisan vendor:publish --tag="filament-trilist-views"
    

    Only needed if customizing Blade templates.

  3. First Use Case:

    • TreeSelect Input: Add to a Filament form:
      use Beholdr\FilamentTrilist\Forms\Components\TreeSelect;
      
      TreeSelect::make('parent_id')
          ->label('Select Parent')
          ->options($this->getTreeData())
          ->required(),
      
    • TreeView Page: Create a resource page:
      use Beholdr\FilamentTrilist\Resources\Pages\TreeViewPage;
      
      public static function getPages(): array
      {
          return [
              TreeViewPage::route('/tree'),
          ];
      }
      
  4. Data Format: Ensure your data follows the required structure:

    [
        ['id' => 1, 'label' => 'Root', 'children' => [...]],
        // ...
    ]
    

    Use staudenmeir/eloquent-eager-trees or similar for Eloquent models.


Implementation Patterns

Common Workflows

1. TreeSelect in Forms

  • Basic Usage:

    TreeSelect::make('category_id')
        ->options($categories->toTree())
        ->searchable()
        ->preload(),
    
    • searchable(): Adds a search input.
    • preload(): Loads children on initial render (useful for large trees).
  • Dynamic Data: Fetch data via a query method:

    TreeSelect::make('parent_id')
        ->options(fn () => $this->getTreeData())
        ->rules(['required']),
    
  • Customizing Labels:

    TreeSelect::make('parent_id')
        ->label('Parent Category')
        ->placeholder('Select a category...'),
    

2. TreeView Page

  • Basic Setup:

    TreeViewPage::make('categories')
        ->header('Category Tree')
        ->columns(3) // Adjust layout
        ->options($categories->toTree()),
    
    • columns(): Controls the number of columns in the tree view.
  • Custom Actions: Add buttons or actions to tree nodes:

    TreeViewPage::make('posts')
        ->actions([
            TreeViewAction::make('edit')
                ->label('Edit')
                ->url(fn ($record) => route('admin.posts.edit', $record)),
        ]),
    

3. Handling Nested Relationships

  • Eloquent Models: Use staudenmeir/eloquent-eager-trees for Eloquent models:

    use Staudenmeir\EloquentEagerTree\Tree;
    
    class Category extends Model implements Tree
    {
        use \Staudenmeir\EloquentEagerTree\HasTree;
    }
    

    Then fetch data:

    $categories = Category::with('children')->get()->toTree();
    
  • Custom Data Sources: For non-Eloquent data (e.g., API responses), transform to the required format:

    $treeData = array_map(fn ($item) => [
        'id' => $item['id'],
        'label' => $item['name'],
        'children' => $item['children'] ?? [],
    ], $apiResponse);
    

4. Integration with Filament Resources

  • TreeSelect in Resource Forms:

    // app/Filament/Resources/CategoryResource.php
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                TreeSelect::make('parent_id')
                    ->options(fn () => Category::query()->toTree())
                    ->required(false),
            ]);
    }
    
  • TreeView as a Resource Page:

    // app/Filament/Resources/CategoryResource/Pages/ManageCategories.php
    public static function getPages(): array
    {
        return [
            TreeViewPage::route('/tree-view'),
        ];
    }
    

5. Styling and Theming

  • Custom CSS: Publish views and override Blade templates (e.g., resources/views/vendor/filament-trilist/...). Example: Modify tree-select.blade.php to change colors or icons.

  • Tailwind Classes: Use Tailwind classes directly in the component:

    TreeSelect::make('parent_id')
        ->class('bg-gray-50 border-gray-300')
        ->searchable(),
    

Gotchas and Tips

Pitfalls and Debugging

1. Data Format Mismatches

  • Issue: TreeSelect/TreeView fails to render or shows empty.
    • Cause: Data doesn’t match the expected format (id, label, children).
    • Fix: Validate your data structure:
      $treeData = collect($rawData)->map(function ($item) {
          return [
              'id' => $item['id'] ?? null,
              'label' => $item['name'] ?? 'Untitled',
              'children' => $item['children'] ?? [],
          ];
      })->toArray();
      

2. Performance with Large Trees

  • Issue: Slow rendering or memory issues with deep/nested trees.
    • Fix:
      • Use preload() to lazy-load children.
      • Limit depth with maxDepth():
        TreeSelect::make('parent_id')
            ->options($treeData)
            ->maxDepth(3),
        
      • Paginate data server-side if possible.

3. Circular References

  • Issue: Infinite loops in tree data (e.g., parent-child cycles).
    • Fix: Use staudenmeir/eloquent-eager-trees with with('children') and validate your model relationships.

4. Caching Tree Data

  • Issue: Repeatedly fetching the same tree data (e.g., in a form).
    • Fix: Cache the tree structure:
      $treeData = Cache::remember('tree-data', now()->addHours(1), function () {
          return Category::query()->toTree();
      });
      

5. Filament Version Conflicts

  • Issue: Package not working with your Filament version.
    • Fix: Check the compatibility table and install the correct version:
      composer require beholdr/filament-trilist:^1.1.x  # For Filament 5.x
      

Tips and Tricks

1. Custom Icons

  • Use Blade directives to customize icons per node:
    TreeViewPage::make('categories')
        ->options($treeData)
        ->icon(fn ($item) => $item['is_root'] ? 'heroicon-o-home' : 'heroicon-o-folder'),
    

2. Search Functionality

  • Enhance search with debouncing:
    TreeSelect::make('parent_id')
        ->searchable()
        ->debounce(300), // 300ms delay
    

3. Disabling Nodes

  • Disable specific nodes (e.g., root or certain categories):
    TreeSelect::make('parent_id')
        ->options($treeData)
        ->disabled(fn ($item) => $item['id'] === 1), // Disable root
    

4. Localization

  • Localize labels and placeholders:
    TreeSelect::make('parent_id')
        ->label(__('filament-trilist::messages.select_parent'))
        ->placeholder(__('filament-trilist::messages.search_or_select')),
    
    Publish translations:
    php artisan vendor:publish --tag="filament-trilist-lang"
    

5. Extending Functionality

  • Custom Actions: Add buttons to TreeView nodes:

    TreeViewPage::make('posts')
        ->actions([
            TreeViewAction::make('delete')
                ->label('Delete')
                ->icon('heroicon-o-trash')
                ->action(fn ($record) => $this->delete($record)),
        ]),
    
  • Event Listeners: Listen to tree interactions:

    TreeSelect::make('parent_id')
        ->options($treeData)
        ->listen('selected', fn ($value) => Log::info("Selected: {$value}")),
    

6. Testing

  • Test TreeSelect/TreeView in feature tests:
    public function test_tree_select()
    {
        $component = TreeSelect::make('parent_id')
            ->options($treeData);
    
        $this->filament()->actingAs($user)
            ->from('admin.resources.categories.edit')
            ->select($component)
            ->assertHasNoFormErrors();
    }
    

7. Debugging Data

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium