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

Laravel Table Laravel Package

gbrock/laravel-table

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require gbrock/laravel-table:dev-master
    

    Register the service provider and facade in config/app.php:

    'providers' => [
        Gbrock\Table\Providers\TableServiceProvider::class,
    ],
    'aliases' => [
        'Table' => Gbrock\Table\Facades\Table::class,
    ]
    

    Publish assets:

    php artisan vendor:publish --provider="Gbrock\Table\Providers\TableServiceProvider"
    
  2. First Use Case: In a controller, create a table from an Eloquent collection:

    use Gbrock\Table\Facades\Table;
    
    public function index()
    {
        $users = User::all();
        $table = Table::create($users);
        return view('users.index', compact('table'));
    }
    
  3. Render in Blade: Use the provided Blade directive @table in your view:

    @table(['table' => $table])
    

Implementation Patterns

Core Workflows

  1. Basic Table Rendering:

    $table = Table::create(User::paginate(10));
    

    Automatically handles pagination via paginate() or cursor().

  2. Customizing Columns: Define columns in the table constructor or via a closure:

    $table = Table::create(User::all())
        ->columns([
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'Email',
            'created_at' => function ($value) {
                return $value->diffForHumans();
            }
        ]);
    
  3. Sortable Columns: Enable sorting for specific columns:

    $table = Table::create(User::orderBy('name')->get())
        ->sortable(['name', 'email']);
    

    Blade will render clickable headers for sorting.

  4. Conditional Cell Data: Use closures to dynamically format cells:

    $table = Table::create(User::all())
        ->column('active', function ($value, $row) {
            return $value ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
        });
    
  5. Integration with Controllers/Repositories: Encapsulate table logic in a repository or service:

    class UserTableService
    {
        public function build(UserRepository $users)
        {
            return Table::create($users->all())
                ->columns(['id', 'name', 'email'])
                ->sortable(['name', 'email']);
        }
    }
    
  6. Pagination Control: Pass paginated results directly:

    $table = Table::create(User::paginate(25));
    

    Or manually set pagination:

    $table = Table::create(User::all())
        ->paginate(25);
    
  7. Reusing Table Configurations: Use the TableBuilder facade to define reusable table configurations:

    Table::builder('users')
        ->columns(['id', 'name', 'email'])
        ->sortable(['name', 'email'])
        ->paginate(25);
    

    Then fetch it in a controller:

    $table = Table::get('users', User::all());
    

Gotchas and Tips

Pitfalls

  1. Deprecated Features:

    • The README mentions "batch action handling" and "user-definable rows-per-page" as "coming soon," but these features are not implemented. Avoid relying on them.
    • The package is last updated in 2015 and lacks Laravel 8/9 compatibility. Test thoroughly for edge cases (e.g., query builder changes).
  2. Pagination Quirks:

    • If using paginate(), ensure your query returns the correct number of results. The package does not modify the underlying query; it only renders pagination controls.
    • Custom pagination logic (e.g., simplePaginate()) may not work as expected. Stick to paginate() or manual pagination.
  3. Sorting Limitations:

    • Sorting is client-side only by default. The package does not automatically re-query the database. Implement server-side sorting by:
      $table = Table::create(User::orderBy(request('sort', 'name'))->get())
          ->sortable(['name', 'email']);
      
      Then handle the sort parameter in your controller.
  4. Blade Directive Scope: The @table directive expects a variable named table. If you pass the table under a different name (e.g., $dataTable), update the directive:

    @table(['table' => $dataTable])
    
  5. CSS/JS Dependencies: The package assumes Bootstrap 3 for styling. If using a different framework (e.g., Tailwind), override the published views (resources/views/vendor/table/).


Debugging Tips

  1. Inspect Table Structure: Dump the table object to understand its configuration:

    dd($table->getColumns(), $table->getSortableColumns());
    
  2. Check Published Views: Override the default views in resources/views/vendor/table/ to customize rendering:

    php artisan vendor:publish --tag=views
    
  3. Handle Missing Columns: If a column doesn’t render, verify:

    • The column name matches the model’s attribute (or accessor).
    • The column is included in the columns() array.
  4. Sorting Debugging: Add logging to track sorting parameters:

    \Log::info('Sort param:', request('sort'));
    

Extension Points

  1. Custom Cell Renderers: Extend the Gbrock\Table\Cell class to create reusable renderers:

    class StatusCell extends Gbrock\Table\Cell
    {
        public function render($value, $row)
        {
            return $value ? 'Active' : 'Inactive';
        }
    }
    

    Use it in your table:

    $table->column('active', new StatusCell());
    
  2. Override Default Views: Publish and modify the Blade views for full control over HTML output:

    php artisan vendor:publish --tag=views
    
  3. Add Custom Actions: Although batch actions are not implemented, you can manually add them to the table footer:

    @table(['table' => $table])
    <div class="table-footer">
        <button class="btn btn-danger">Delete Selected</button>
    </div>
    
  4. Integrate with Laravel Mix: If using Laravel Mix, ensure the package’s assets (if any) are compiled. The package is lightweight, but you may need to manually include Bootstrap JS/CSS if not already loaded.


Performance Notes

  • Avoid Over-Fetching: Ensure your Eloquent query only retrieves necessary columns:
    $table = Table::create(User::select('id', 'name', 'email')->get());
    
  • Lazy Loading: For large datasets, use cursor() instead of get() to reduce memory usage:
    $table = Table::create(User::cursor());
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky