Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Blaze
https://github.com/livewire/blaze
Admin
Blaze is a Laravel package that optimizes Blade component rendering by compiling templates into
...
Tokens:
26,402
Snippets:
126
Trust Score:
7.4
Update:
1 month ago
Context
Skills
Chat
Benchmark
90.9
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Blaze Blaze is a high-performance Laravel package that optimizes Blade component rendering by compiling templates into optimized PHP functions. It serves as a drop-in replacement for anonymous Blade components, eliminating 91-97% of rendering overhead while maintaining near-full feature parity with standard Blade. The package achieves dramatic performance improvements—rendering 25,000 components in 13ms compared to Blade's 500ms—by bypassing the standard rendering pipeline. Beyond the default function compilation, Blaze offers two advanced optimization strategies for even greater performance gains. Runtime Memoization caches repeated component renders based on their props, ideal for icons and avatars that appear multiple times on a page. Compile-Time Folding pre-renders components into static HTML during compilation, achieving constant rendering time regardless of component count but requiring careful consideration of dynamic content and global state. ## Installation Install Blaze via Composer to add optimized Blade component rendering to your Laravel application. ```bash composer require livewire/blaze:^1.0@beta ``` After installation, clear compiled views to enable Blaze: ```bash php artisan view:clear ``` ## @blaze Directive The `@blaze` directive enables Blaze optimization for individual anonymous components. Add it to the top of any component file to activate function compilation, with optional parameters for additional optimization strategies. ```blade {{-- resources/views/components/button.blade.php --}} @blaze @props(['type' => 'button', 'variant' => 'primary']) @php $classes = match($variant) { 'primary' => 'bg-blue-500 hover:bg-blue-400 text-white', 'secondary' => 'bg-gray-200 hover:bg-gray-300 text-gray-800', 'danger' => 'bg-red-500 hover:bg-red-400 text-white', default => 'bg-gray-500 text-white', }; @endphp <button type="{{ $type }}" {{ $attributes->class($classes) }}> {{ $slot }} </button> ``` Usage in parent templates: ```blade {{-- resources/views/welcome.blade.php --}} <x-button type="submit" variant="primary"> Save Changes </x-button> <x-button variant="danger" class="ml-2"> Delete </x-button> ``` ## Blaze::optimize() - Directory Configuration Configure Blaze optimization for entire directories from your service provider using the fluent `optimize()` API. This approach is ideal for optimizing many components at once without modifying individual files. ```php <?php // app/Providers/AppServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Livewire\Blaze\Blaze; class AppServiceProvider extends ServiceProvider { public function boot(): void { // Enable Blaze for all components in a directory Blaze::optimize()->in(resource_path('views/components')); // Enable for specific subdirectories with different strategies Blaze::optimize() ->in(resource_path('views/components/ui')) ->in(resource_path('views/components/icons'), memo: true) ->in(resource_path('views/components/cards'), fold: true); // Exclude specific directories from compilation Blaze::optimize() ->in(resource_path('views/components')) ->in(resource_path('views/components/legacy'), compile: false); } } ``` ## Runtime Memoization Enable memoization to cache component output when the same props are used multiple times on a page. This strategy is ideal for icons, avatars, and other frequently repeated elements without slots. ```blade {{-- resources/views/components/icon.blade.php --}} @blaze(memo: true) @props(['name', 'size' => 'md']) @php $sizeClasses = match($size) { 'sm' => 'w-4 h-4', 'md' => 'w-6 h-6', 'lg' => 'w-8 h-8', default => 'w-6 h-6', }; @endphp <svg {{ $attributes->class($sizeClasses) }}> <use href="/icons.svg#{{ $name }}" /> </svg> ``` Usage showing memoization benefits: ```blade {{-- These render only once each, subsequent calls use cached output --}} @foreach($tasks as $task) <div class="flex items-center gap-2"> <x-icon :name="$task->status->icon" size="sm" /> <span>{{ $task->title }}</span> <x-icon name="chevron-right" size="sm" /> </div> @endforeach ``` ## Compile-Time Folding Enable folding to pre-render components into static HTML during compilation. This eliminates all runtime overhead but requires careful consideration—components must not use global state, and dynamic props need special handling. ```blade {{-- resources/views/components/badge.blade.php --}} @blaze(fold: true) @props(['color' => 'gray']) @php $colorClasses = match($color) { 'green' => 'bg-green-100 text-green-800', 'red' => 'bg-red-100 text-red-800', 'blue' => 'bg-blue-100 text-blue-800', 'yellow' => 'bg-yellow-100 text-yellow-800', default => 'bg-gray-100 text-gray-800', }; @endphp <span {{ $attributes->class(['px-2 py-1 rounded-full text-xs font-medium', $colorClasses]) }}> {{ $slot }} </span> ``` Usage with static props (folds successfully): ```blade {{-- This gets compiled to static HTML at compile time --}} <x-badge color="green">Active</x-badge> <x-badge color="red">Inactive</x-badge> {{-- Output after compilation: --}} {{-- <span class="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">Active</span> --}} ``` ## Selective Folding with safe and unsafe Control folding behavior for specific props and slots using the `safe` and `unsafe` parameters. Mark pass-through props as `safe` to allow folding even when dynamic, or mark transformed props/slots as `unsafe` to abort folding when they receive dynamic values. ```blade {{-- resources/views/components/heading.blade.php --}} {{-- 'level' is pass-through (not transformed), so mark it safe --}} @blaze(fold: true, safe: ['level']) @props(['level' => 2]) <h{{ $level }} {{ $attributes }}>{{ $slot }}</h{{ $level }}> ``` ```blade {{-- resources/views/components/conditional-wrapper.blade.php --}} {{-- Slot is used in conditional logic, mark as unsafe --}} @blaze(fold: true, unsafe: ['slot']) @if ($slot->hasActualContent()) <div class="wrapper">{{ $slot }}</div> @else <div class="empty-state">No content provided</div> @endif ``` ```blade {{-- resources/views/components/link.blade.php --}} {{-- href is read from attributes for logic, mark as unsafe --}} @blaze(fold: true, unsafe: ['href']) @php $isActive = $attributes->get('href') === url()->current(); @endphp <a {{ $attributes->class(['nav-link', 'active' => $isActive]) }}> {{ $slot }} </a> ``` Usage examples: ```blade {{-- Dynamic level is safe because it's pass-through --}} <x-heading :level="$section->importance">{{ $section->title }}</x-heading> {{-- Dynamic href triggers fallback to function compilation --}} <x-link :href="route('dashboard')">Dashboard</x-link> {{-- Self-closing still folds, only slot content triggers abort --}} <x-conditional-wrapper /> {{-- Folds --}} <x-conditional-wrapper>Content</x-conditional-wrapper> {{-- Falls back --}} ``` ## @unblaze Directive Use `@unblaze` to exclude dynamic sections from folding while keeping the rest of the component optimized. Variables from the component scope must be passed explicitly via the `scope` parameter. ```blade {{-- resources/views/components/form-field.blade.php --}} @blaze(fold: true) @props(['name', 'label', 'type' => 'text']) <div class="form-group"> <label for="{{ $name }}" class="block text-sm font-medium text-gray-700"> {{ $label }} </label> <input type="{{ $type }}" name="{{ $name }}" id="{{ $name }}" {{ $attributes->class('mt-1 block w-full rounded-md border-gray-300 shadow-sm') }} > @unblaze(scope: ['name' => $name]) @error($scope['name']) <p class="mt-1 text-sm text-red-600">{{ $message }}</p> @enderror @endunblaze </div> ``` Usage: ```blade <form method="POST" action="/register"> @csrf <x-form-field name="email" label="Email Address" type="email" /> <x-form-field name="password" label="Password" type="password" /> <x-button type="submit">Register</x-button> </form> ``` ## Debug Mode Enable debug mode to measure rendering performance, compare Blaze against standard Blade, and identify bottlenecks using the built-in profiler and overlay. ```php <?php // app/Providers/AppServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Livewire\Blaze\Blaze; class AppServiceProvider extends ServiceProvider { public function boot(): void { // Enable debug mode programmatically Blaze::debug(); // Or enable via environment variable in .env: // BLAZE_DEBUG=true // Configure components Blaze::optimize()->in(resource_path('views/components')); } } ``` To compare Blade vs Blaze performance: ```bash # Step 1: Disable Blaze and record baseline echo "BLAZE_ENABLED=false" >> .env php artisan view:clear # Visit pages to record Blade times # Step 2: Re-enable Blaze and compare sed -i '/BLAZE_ENABLED/d' .env php artisan view:clear # Visit same pages to see Blaze times and savings ``` ## Blaze::enable() and Blaze::disable() Control Blaze compilation at runtime for conditional optimization or testing scenarios. ```php <?php // app/Providers/AppServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Livewire\Blaze\Blaze; class AppServiceProvider extends ServiceProvider { public function boot(): void { // Disable Blaze in specific environments if (app()->environment('testing')) { Blaze::disable(); return; } // Enable and configure for production Blaze::enable(); Blaze::optimize()->in(resource_path('views/components')); } } ``` ## Blaze::throw() Enable throw mode to surface exceptions during folding instead of silently falling back to function compilation. Useful for debugging and ensuring components are properly configured. ```php <?php // app/Providers/AppServiceProvider.php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Livewire\Blaze\Blaze; class AppServiceProvider extends ServiceProvider { public function boot(): void { // In development, throw exceptions to catch folding issues early if (app()->environment('local')) { Blaze::throw(); } Blaze::optimize() ->in(resource_path('views/components')) ->in(resource_path('views/components/static'), fold: true); } } ``` ## Environment Variables Configure Blaze behavior through environment variables without code changes. ```env # .env # Enable or disable Blaze compilation entirely (default: true) BLAZE_ENABLED=true # Enable debug mode with overlay and profiler (default: false) BLAZE_DEBUG=false ``` ```php <?php // config/blaze.php (published via: php artisan vendor:publish --tag=blaze:config) return [ // When false, Blaze skips all compilation and optimization 'enabled' => env('BLAZE_ENABLED', true), // When true, registers debugger middleware and outputs diagnostics 'debug' => env('BLAZE_DEBUG', false), ]; ``` ## BlazeAttributeBag Blaze uses an optimized `BlazeAttributeBag` that provides the same API as Laravel's `ComponentAttributeBag` with reduced overhead. It supports all standard attribute manipulation methods. ```blade {{-- resources/views/components/input.blade.php --}} @blaze @props(['type' => 'text', 'error' => false]) <input type="{{ $type }}" {{ $attributes ->class([ 'block w-full rounded-md shadow-sm', 'border-gray-300 focus:border-indigo-500' => !$error, 'border-red-300 focus:border-red-500' => $error, ]) ->merge(['autocomplete' => 'off']) }} > ``` ```blade {{-- resources/views/components/card.blade.php --}} @blaze @props(['padding' => true]) <div {{ $attributes ->class(['bg-white rounded-lg shadow']) ->merge(['class' => $padding ? 'p-6' : '']) ->whereDoesntStartWith('wire:') }}> {{ $slot }} </div> ``` ## @aware Directive Support Blaze supports the `@aware` directive for accessing parent component data, but both parent and child components must use Blaze for values to propagate correctly. ```blade {{-- resources/views/components/tabs.blade.php --}} @blaze @props(['active' => null]) <div {{ $attributes->class('border-b border-gray-200') }} x-data="{ active: '{{ $active }}' }"> {{ $slot }} </div> ``` ```blade {{-- resources/views/components/tab.blade.php --}} @blaze @props(['name']) @aware(['active']) <button {{ $attributes->class([ 'px-4 py-2 font-medium text-sm', 'text-indigo-600 border-b-2 border-indigo-600' => $active === $name, 'text-gray-500 hover:text-gray-700' => $active !== $name, ]) }} x-on:click="active = '{{ $name }}'" > {{ $slot }} </button> ``` Usage: ```blade <x-tabs active="profile"> <x-tab name="profile">Profile</x-tab> <x-tab name="settings">Settings</x-tab> <x-tab name="notifications">Notifications</x-tab> </x-tabs> ``` ## Memo API The `Memo` class provides the runtime caching mechanism for memoized components. It generates cache keys from component names and props, storing rendered output for reuse within the same request. ```php <?php use Livewire\Blaze\Memoizer\Memo; // Generate a cache key from component name and props $key = Memo::key('icon', ['name' => 'check', 'size' => 'md']); // Returns: 'blaze_memoized_icon:a1b2c3d4...' // Check if output is cached if (Memo::has($key)) { echo Memo::get($key); } else { // Render and cache $html = '<svg class="w-6 h-6">...</svg>'; Memo::put($key, $html); echo $html; } // Clear all memoized entries (useful in tests) Memo::clear(); // Remove specific entry Memo::forget($key); // Non-serializable props return null key (skip caching) $key = Memo::key('component', ['callback' => fn() => 'test']); // Returns: null ``` Blaze is designed to be a seamless performance upgrade for Laravel applications using anonymous Blade components. The default function compilation strategy works for virtually all components and provides significant performance improvements without any configuration changes. For applications with repeated components like icon libraries or design systems, memoization offers additional gains with minimal setup. For maximum performance in specific use cases, compile-time folding can eliminate rendering overhead entirely, but requires understanding its constraints around dynamic content and global state. The `@unblaze` directive and `safe`/`unsafe` parameters provide fine-grained control for components that mix static and dynamic content. Whether optimizing an entire component library or targeting specific performance bottlenecks, Blaze's layered approach allows gradual adoption while maintaining full compatibility with existing Blade templates.