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 View Components Laravel Package

spatie/laravel-view-components

Abandoned package. Provides a “view components” pattern for Laravel: classes implementing Htmlable that encapsulate view-related logic and render HTML (often via Blade). Use @render to pass data, and wrap third‑party HTML builders like menus.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-view-components
    

    (Note: Despite being archived, the package remains functional for Laravel 5.6+.)

  2. First Component: Create a class implementing Illuminate\Contracts\Support\Htmlable (e.g., app/Http/ViewComponents/NavigationComponent.php):

    namespace App\Http\ViewComponents;
    
    use Illuminate\Http\Request;
    use Illuminate\Contracts\Support\Htmlable;
    
    class NavigationComponent implements Htmlable
    {
        public function __construct(public Request $request) {}
    
        public function toHtml(): string
        {
            return '<nav>...</nav>';
        }
    }
    
  3. Register in Blade: Add to config/app.php under view > components:

    'components' => [
        'navigation' => App\Http\ViewComponents\NavigationComponent::class,
    ],
    

    Use in Blade:

    @component('navigation')
    @endcomponent
    

First Use Case

Replace a static navigation partial with a dynamic component:

// Component logic fetches active routes, user permissions, etc.
public function toHtml(): string
{
    $active = $this->request->path() === 'dashboard';
    return view('components.navigation', ['active' => $active]);
}

Implementation Patterns

Dependency Injection

  • Constructor Injection: Pass services (e.g., Request, Auth) directly:
    public function __construct(
        public Request $request,
        public UserRepository $users
    ) {}
    
  • Lazy Loading: Use with() in Blade to pass data:
    @component('navigation', ['color' => 'dark'])
    @endcomponent
    

Blade Integration

  • Slot-Based Components: Extend Blade slots for nested content:
    public function toHtml(): string
    {
        return view('components.card', [
            'title' => 'Slot Example',
        ]);
    }
    
    @component('card')
        @slot('content')
            {{ $slot }}
        @endslot
    @endcomponent
    

Data Fetching

  • Eager Load Dependencies: Resolve heavy dependencies (e.g., Eloquent models) in __construct:
    public function __construct(public Post $post) {}
    
  • Caching: Cache component output via middleware or toHtml():
    public function toHtml(): string
    {
        return Cache::remember("nav_{$this->request->path()}", now()->addHour(), function () {
            return view('components.navigation')->render();
        });
    }
    

Testing

  • Mock Components: Test in isolation:
    $component = new NavigationComponent(
        $mockRequest,
        $mockUserRepository
    );
    $this->assertStringContainsString('Dashboard', $component->toHtml());
    
  • Blade Rendering: Test Blade output:
    $blade = new BladeOne($viewFactory);
    $this->assertEquals('<nav>...</nav>', $blade->renderComponent('navigation'));
    

Gotchas and Tips

Pitfalls

  1. Archived Package:

    • No new features; use alternatives like Livewire or Blade Components (Laravel 7+).
    • Fork or maintain locally if critical.
  2. Blade Cache Invalidation:

    • Clear bootstrap/cache after adding new components:
      php artisan view:clear
      
  3. Circular Dependencies:

    • Avoid components that instantiate other components in __construct (use lazy loading).

Debugging

  • Component Not Found:

    • Verify config/app.php registration and namespace.
    • Check for typos in Blade @component('name').
  • Missing Dependencies:

    • Ensure all constructor arguments are resolvable by Laravel’s container.

Extension Points

  1. Custom Htmlable: Extend Htmlable for non-string outputs (e.g., JSON):

    class ApiComponent implements Htmlable
    {
        public function toHtml(): string
        {
            return response()->json(['data' => []])->getContent();
        }
    }
    
  2. Dynamic Registration: Register components dynamically in a service provider:

    View::addComponent('dynamic', function () {
        return new DynamicComponent();
    });
    
  3. Legacy Blade Support: Use {{ $component->render() }} if toHtml() fails in older Laravel versions.

Performance

  • Avoid Heavy Logic in toHtml: Offload processing to __construct or services.
  • Component Caching: Cache entire component output for static pages:
    public function toHtml(): string
    {
        return Cache::rememberForever('footer_component', function () {
            return view('components.footer')->render();
        });
    }
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport