Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Add Docs
Blade Icons
https://github.com/driesvints/blade-icons
Admin
A package to easily make use of SVG icons in your Laravel Blade views, allowing for simple
...
Tokens:
9,839
Snippets:
109
Trust Score:
9
Update:
2 weeks ago
Context
Skills
Chat
Benchmark
93.2
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Blade Icons Blade Icons is a Laravel package that simplifies the usage of SVG icons in Blade views. Originally created as "Blade SVG" by Adam Wathan, it transforms raw SVG files into reusable Blade components, directives, and helper functions. The package supports multiple icon sets with unique prefixes, custom CSS classes, default attributes, fallback icons, and filesystem disk integration for external storage like AWS S3. The core functionality revolves around registering icon sets with configurable paths and prefixes, then rendering those icons through three primary methods: Blade components (`<x-icon-name/>`), the `@svg` directive, or the `svg()` helper function. The package includes caching capabilities for production environments, accessibility features with title attributes, and a deferred rendering system to optimize DOM performance when the same icon appears multiple times on a page. ## Installation Install the package via Composer and publish the configuration file. ```bash # Install the package composer require blade-ui-kit/blade-icons # Publish the configuration file php artisan vendor:publish --tag=blade-icons ``` ## Configuration - Defining Icon Sets Configure icon sets in `config/blade-icons.php` by specifying paths, prefixes, default classes, and attributes for each set. ```php <?php // config/blade-icons.php return [ 'sets' => [ 'default' => [ // Path to SVG icons relative to app root 'path' => 'resources/svg', // Required unique prefix for this set 'prefix' => 'icon', // Fallback icon when requested icon not found 'fallback' => 'placeholder', // Default CSS classes for all icons in this set 'class' => 'icon icon-default', // Default HTML attributes 'attributes' => [ 'width' => 24, 'height' => 24, ], ], 'heroicons' => [ 'path' => 'resources/icons/heroicons', 'prefix' => 'heroicon', 'class' => 'heroicon', ], ], // Global default classes applied to all icons 'class' => '', // Global default attributes 'attributes' => [], // Global fallback icon (can reference any set) 'fallback' => 'icon-placeholder', 'components' => [ // Set to true to disable Blade components entirely 'disabled' => false, // Name for the default <x-icon> component 'default' => 'icon', ], ]; ``` ## Configuration - Multiple Paths per Set Define multiple directories for a single icon set using the `paths` option. ```php <?php // config/blade-icons.php return [ 'sets' => [ 'default' => [ 'paths' => [ 'resources/icons/solid', 'resources/icons/outline', 'resources/icons/custom', ], 'prefix' => 'icon', ], ], ]; ``` ## Configuration - Filesystem Disk Load icons from external storage like AWS S3 by configuring a filesystem disk. ```php <?php // config/blade-icons.php return [ 'sets' => [ 'heroicons' => [ 'path' => 'heroicons', // Path within the disk 'disk' => 's3-icons', // Disk name from filesystems.php 'prefix' => 'heroicon', ], 'zondicons' => [ 'path' => 'zondicons', 'disk' => 's3-icons', 'prefix' => 'zondicon', ], ], ]; ``` ## Blade Components - Basic Usage Use icons as Blade components with the format `<x-{prefix}-{icon-name}/>`. Icons in subdirectories use dot notation. ```blade {{-- Basic icon usage (from default set with 'icon' prefix) --}} <x-icon-camera/> {{-- Icon from subdirectory resources/svg/solid/camera.svg --}} <x-icon-solid.camera/> {{-- Icon from heroicons set --}} <x-heroicon-bell/> {{-- With CSS classes --}} <x-icon-camera class="w-6 h-6 text-gray-500"/> {{-- With additional attributes --}} <x-icon-camera class="icon-lg" id="settings-icon" style="color: #555" data-tooltip="Camera" /> {{-- Output example --}} {{-- <svg class="w-6 h-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2..."/> </svg> --}} ``` ## Blade Components - Default Icon Component Use the `<x-icon>` component with a `name` attribute for dynamic icon selection. ```blade {{-- Using the default Icon component --}} <x-icon name="camera"/> {{-- With icon from another set (include prefix) --}} <x-icon name="heroicon-bell"/> {{-- With classes and attributes --}} <x-icon name="camera" class="w-8 h-8" id="main-icon"/> {{-- Dynamic icon name from variable --}} <x-icon :name="$iconName" class="icon-sm"/> {{-- Configure custom component name in config/blade-icons.php --}} {{-- 'components' => ['default' => 'svg'] --}} <x-svg name="camera"/> ``` ## Blade Components - Deferred Icons Defer icon rendering to reduce DOM size when the same icon appears multiple times on a page. ```blade {{-- Add defer attribute to defer icon rendering --}} <x-icon-camera defer/> <x-icon-camera defer/> <x-icon-camera defer/> {{-- Custom hash for JavaScript reuse --}} <x-icon-camera defer="camera-icon"/> {{-- At the bottom of your layout, load the deferred icons --}} <svg hidden class="hidden"> @stack('bladeicons') </svg> </body> </html> {{-- In JavaScript, reference deferred icons by hash --}} {{-- <script> function renderIcon() { return '<svg><use href="#icon-camera-icon"></use></svg>'; } </script> --}} ``` ## Blade Directive - @svg The `@svg` directive provides an alternative syntax for rendering icons with classes and attributes. ```blade {{-- Basic usage --}} @svg('camera') {{-- With CSS class --}} @svg('camera', 'w-6 h-6') {{-- With class and additional attributes --}} @svg('camera', 'icon-lg', ['id' => 'settings-icon', 'data-foo' => 'bar']) {{-- Attributes only (no class) --}} @svg('camera', ['id' => 'settings-icon']) {{-- Override default classes via attributes --}} @svg('camera', ['class' => 'custom-class-only']) {{-- Boolean attributes (without value) --}} @svg('camera', ['data-foo']) {{-- Icon from another set (use prefix) --}} @svg('heroicon-bell', 'w-5 h-5') {{-- Icon in subdirectory --}} @svg('solid.camera', 'w-4 h-4') ``` ## Helper Function - svg() The `svg()` helper function returns an `Svg` object with a fluent interface for setting attributes. ```php {{-- Basic usage in Blade --}} {{ svg('camera') }} {{-- With class --}} {{ svg('camera', 'w-6 h-6') }} {{-- With attributes array --}} {{ svg('camera', 'icon-lg', ['id' => 'camera-icon']) }} {{-- Fluent attribute setting --}} {{ svg('camera')->id('settings-icon')->dataFoo('bar')->dataBaz() }} {{-- In PHP code --}} <?php use function svg; // Get SVG object $icon = svg('camera', 'w-6 h-6', ['id' => 'my-icon']); // Access properties $name = $icon->name(); // Returns: 'camera' $contents = $icon->contents(); // Returns: SVG markup string $attributes = $icon->attributes(); // Returns: ['class' => 'w-6 h-6', 'id' => 'my-icon'] // Render to HTML $html = $icon->toHtml(); // Fluent API $icon = svg('camera') ->class('w-6 h-6') ->id('icon-1') ->dataTooltip('Camera Icon') ->ariaHidden(); echo $icon->toHtml(); // Output: <svg class="w-6 h-6" id="icon-1" data-tooltip="Camera Icon" aria-hidden...> ``` ## Accessibility - Title Attribute Add accessible titles to icons for screen readers and SEO compliance. ```blade {{-- Using component --}} <x-icon-camera title="Camera"/> {{-- Using directive --}} @svg('camera', ['title' => 'Camera']) {{-- Using helper --}} {{ svg('camera', '', ['title' => 'Camera']) }} {{-- Output --}} {{-- <svg title="Camera" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" > <title>Camera</title> <path fill="currentColor" d="M438.6..."></path> </svg> --}} {{-- For decorative icons, hide from assistive technology --}} <x-icon-camera aria-hidden="true"/> ``` ## Factory - Registering Icon Sets Programmatically Register custom icon sets from service providers using the Factory class. ```php <?php namespace App\Providers; use BladeUI\Icons\Factory; use Illuminate\Support\ServiceProvider; class IconServiceProvider extends ServiceProvider { public function register(): void { // Register icon set after Factory is resolved $this->callAfterResolving(Factory::class, function (Factory $factory) { // Basic registration $factory->add('heroicons', [ 'path' => __DIR__.'/../../resources/icons/heroicons', 'prefix' => 'heroicon', ]); // Full options $factory->add('custom-icons', [ 'paths' => [ __DIR__.'/../../resources/icons/outline', __DIR__.'/../../resources/icons/solid', ], 'prefix' => 'custom', 'fallback' => 'placeholder', 'class' => 'custom-icon', 'attributes' => [ 'width' => 20, 'height' => 20, ], ]); // With filesystem disk $factory->add('remote-icons', [ 'path' => '/icons', 'disk' => 's3', 'prefix' => 'remote', ]); }); } } ``` ## Factory - Retrieving SVG Programmatically Use the Factory class to retrieve and manipulate SVG icons in PHP code. ```php <?php use BladeUI\Icons\Factory; use BladeUI\Icons\Svg; use BladeUI\Icons\Exceptions\SvgNotFound; // Resolve factory from container $factory = app(Factory::class); // Get SVG with optional class and attributes $svg = $factory->svg('camera'); $svg = $factory->svg('camera', 'w-6 h-6'); $svg = $factory->svg('camera', 'icon-lg', ['id' => 'my-icon']); // Get SVG from specific set using prefix $svg = $factory->svg('heroicon-bell', 'w-5 h-5'); // Handle missing icons try { $svg = $factory->svg('nonexistent-icon'); } catch (SvgNotFound $e) { // Icon not found and no fallback configured $svg = $factory->svg('fallback-icon'); } // Get all registered icon sets $sets = $factory->all(); // Returns: ['default' => [...], 'heroicons' => [...]] // Render SVG to HTML string $html = $svg->toHtml(); ``` ## Artisan Commands - Caching Cache icon manifests for production to improve performance with large icon libraries. ```bash # Generate icon cache manifest (recommended for production) php artisan icons:cache # Output: Blade icons manifest file generated successfully! # Creates: bootstrap/cache/blade-icons.php # Clear the icon cache php artisan icons:clear # Output: Blade icons manifest file cleared! # After adding new icons or changing paths, always clear cache php artisan icons:clear php artisan icons:cache # Clear view cache when renaming icon directories php artisan view:clear # Include in deployment scripts php artisan icons:cache ``` ## Icon Generation - Building Icon Packages Generate icons from source directories using a configuration file for building icon packages. ```php <?php // config/generation.php use Symfony\Component\Finder\SplFileInfo; return [ [ // Source directory (e.g., from npm package) 'source' => __DIR__.'/../node_modules/heroicons/outline', // Destination for generated icons 'destination' => __DIR__.'/../resources/svg', // Strip prefix from source filenames 'input-prefix' => 'o-', // Add prefix to destination filenames 'output-prefix' => 'outline-', // Strip suffix from source filenames 'input-suffix' => '-outline', // Add suffix to destination filenames 'output-suffix' => '-o', // Preserve existing icons in destination (don't delete) 'safe' => true, // Post-processing callback 'after' => static function (string $pathname, array $config, SplFileInfo $file) { // Modify the generated SVG file $content = file_get_contents($pathname); $content = str_replace('stroke-width="2"', 'stroke-width="1.5"', $content); file_put_contents($pathname, $content); }, ], // Additional icon sets [ 'source' => __DIR__.'/../node_modules/heroicons/solid', 'destination' => __DIR__.'/../resources/svg', 'output-prefix' => 'solid-', ], ]; ``` ```bash # Run icon generation from package root vendor/bin/blade-icons-generate ``` ## Icon Generation - Programmatic Usage Use the IconGenerator class directly in PHP code. ```php <?php use BladeUI\Icons\Generation\IconGenerator; // Create generator with configuration $generator = IconGenerator::create([ [ 'source' => '/path/to/source/icons', 'destination' => '/path/to/destination', 'output-prefix' => 'custom-', 'safe' => false, ], ]); // Alternative: instantiate directly $generator = new IconGenerator([ [ 'source' => resource_path('raw-icons'), 'destination' => resource_path('svg'), 'input-suffix' => '-icon', 'after' => function ($pathname, $config, $file) { // Add class to all SVGs $content = file_get_contents($pathname); $content = str_replace('<svg', '<svg class="icon"', $content); file_put_contents($pathname, $content); }, ], ]); // Generate icons $generator->generate(); ``` ## Svg Class - Working with SVG Objects The Svg class provides methods to access and manipulate SVG content and attributes. ```php <?php use BladeUI\Icons\Svg; // SVG is typically retrieved via Factory or svg() helper $svg = svg('camera', 'w-6 h-6', ['id' => 'cam']); // Get icon name echo $svg->name(); // Output: camera // Get raw SVG contents (without wrapper attributes) echo $svg->contents(); // Output: <svg fill="none" viewBox="0 0 24 24">...</svg> // Get all attributes $attrs = $svg->attributes(); // Output: ['class' => 'w-6 h-6', 'id' => 'cam'] // Render complete HTML with attributes merged echo $svg->toHtml(); // Output: <svg class="w-6 h-6" id="cam" fill="none" viewBox="0 0 24 24">...</svg> // Fluent attribute methods (uses __call magic) $svg = svg('camera') ->class('icon') ->id('icon-1') ->width('24') ->height('24') ->dataAction('open') ->ariaLabel('Camera icon'); // Boolean attributes (no value) $svg = svg('camera')->ariaHidden(); // Adds: aria-hidden echo $svg->toHtml(); ``` Blade Icons serves as both a standalone solution for managing custom SVG icons and a foundation for third-party icon package development. It is commonly used in Laravel applications to manage application-specific icons stored in `resources/svg`, integrate popular icon libraries like Heroicons, Font Awesome, or Tabler Icons through community packages, and maintain consistent icon styling across components with default classes and attributes. The package integrates seamlessly into Laravel's ecosystem through auto-discovery, Blade component registration, and artisan commands. For production deployments, the caching system significantly improves performance by pre-compiling icon manifests. When building custom icon packages, the generation system automates the process of importing icons from npm packages or other sources, applying transformations, and organizing them into Laravel-ready sets. The accessibility features ensure icons can be properly labeled for screen readers, making it suitable for applications requiring WCAG compliance.