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

Volt Laravel Package

livewire/volt

Volt is a functional API for Livewire that supports single-file components, letting you write a component’s PHP logic and Blade template together in one file for a cleaner, more streamlined workflow.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require livewire/volt
    

    Volt integrates seamlessly with Livewire, so no additional configuration is required beyond ensuring Livewire is installed (livewire/livewire).

  2. First Component: Generate a Volt component using the Artisan command:

    php artisan make:volt Counter
    

    This creates a single-file component (resources/views/livewire/counter.volt.php) with both PHP logic and Blade template in one file.

  3. Basic Usage:

    // resources/views/livewire/counter.volt.php
    <div>
        <button wire:click="increment">Count: <?php echo $count; ?></button>
    </div>
    
    <?php
    class Counter extends Livewire\Component
    {
        public int $count = 0;
    
        public function increment()
        {
            $this->count++;
        }
    }
    
  4. Render in Blade:

    @livewire('counter')
    

Key Starting Points

  • Official Docs: Livewire Volt Documentation
  • Artisan Commands:
    • make:volt – Generate new Volt components.
    • make:volt --class – Generate class-based Volt components (for Laravel 10+).
  • Volt Facade: Use Volt::mount() or Volt::route() for dynamic rendering.

Implementation Patterns

1. Single-File Components

Volt’s strength lies in combining PHP logic and Blade templates in one file. This reduces context-switching and simplifies small-to-medium components.

Example: Form Handling

<!-- resources/views/livewire/contact-form.volt.php -->
<div>
    <form wire:submit.prevent="submit">
        <input type="text" wire:model="name" placeholder="Name">
        <textarea wire:model="message" placeholder="Message"></textarea>
        <button type="submit">Send</button>
    </form>
</div>

<?php
class ContactForm extends Livewire\Component
{
    public string $name = '';
    public string $message = '';

    public function submit()
    {
        $this->validate([
            'name' => 'required',
            'message' => 'required|min:10',
        ]);

        // Process form...
    }
}

2. Functional API for Dynamic Rendering

Use the Volt facade to mount components dynamically, especially useful for:

  • Conditional Rendering:
    <?php if ($showComponent): ?>
        <?php Volt::mount('counter'); ?>
    <?php endif; ?>
    
  • Route-Based Components:
    Route::get('/dashboard', function () {
        return Volt::route('dashboard-component');
    });
    

3. State Management

Leverage Volt’s state options for advanced use cases:

<?php Volt::mount('user-profile', [
    'userId' => 1,
    'options' => [
        'title' => 'User Profile',
        'key' => 'user-profile-' . $userId,
        'only' => ['name', 'email'], // Only sync these properties
    ],
]); ?>

4. Testing

Volt integrates with Laravel’s testing tools:

public function test_volt_component()
{
    $this->livewire(Volt::class)
         ->assertSeeVolt('counter'); // Assert component is rendered
}

5. Class-Based Components (Laravel 10+)

For larger components, use the --class flag:

php artisan make:volt UserProfile --class

This generates a separate PHP class (app/Livewire/UserProfile.php) with the template in resources/views/livewire/user-profile.blade.php.


Gotchas and Tips

Common Pitfalls

  1. View Path Configuration: Ensure livewire.view_path in config/livewire.php points to resources/views (default). Volt relies on this for component resolution.

    'view_path' => resource_path('views'),
    
  2. Blade vs. PHP Syntax: Volt files use .volt.php extension. Avoid mixing @php directives with raw PHP blocks—stick to one style per component for clarity.

  3. Component Aliases: If using custom view paths or namespaces, ensure aliases are configured in config/livewire.php:

    'component_namespace' => 'App\\Livewire',
    
  4. State Property Serialization: Volt’s state properties must be public. Avoid private/protected properties for reactive data:

    // ❌ Avoid
    protected $hidden = true;
    
    // ✅ Use public
    public bool $isHidden = false;
    
  5. Route Caching Issues: If you encounter Segmentation fault during route:cache, ensure Volt’s precompiler is compatible with your Laravel version (see #42).


Debugging Tips

  1. Check Volt Logs: Enable Livewire debugging in .env:

    LIVEWIRE_DEBUG=true
    

    This logs component lifecycle events to the browser console.

  2. Precompiler Errors: If Volt fails to compile, clear cached views:

    php artisan view:clear
    php artisan cache:clear
    
  3. State Not Updating: Ensure properties are marked as public and not modified outside Livewire’s reactivity system (e.g., avoid $this->property = $value in non-wire methods).


Extension Points

  1. Custom Precompiler: Override Volt’s precompiler logic by publishing and modifying the config:

    php artisan vendor:publish --tag="volt-config"
    

    Edit config/volt.php to customize compilation behavior.

  2. Testing Helpers: Extend Volt’s testing methods by creating custom assertions:

    use Livewire\Volt\Testing\VoltTestCase;
    
    class CustomVoltTestCase extends VoltTestCase
    {
        public function assertVoltHasClass($selector, $class)
        {
            $this->assertStringContainsString($class, $this->getLivewireHtml());
        }
    }
    
  3. Integration with Folio: For Folio-based projects, use Volt’s anonymous components:

    Volt::mount('user-card', ['user' => $user], 'user-card');
    

    Ensure the component name matches Folio’s expected namespace.


Performance Considerations

  1. Avoid Heavy Logic in Render: Offload complex logic to methods called via wire:click or wire:change to minimize re-renders.

  2. Lazy-Load Components: Use wire:ignore for non-reactive elements to reduce payload size:

    <div wire:ignore>
        <!-- Non-reactive content -->
    </div>
    
  3. Memoization: Cache expensive computations in properties:

    public function getExpensiveData()
    {
        return $this->state->expensiveData ?? ($this->state->expensiveData = fetchData());
    }
    
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
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
twbs/bootstrap4