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

Cssembed Laravel Package

ptachoire/cssembed

Embed and inline images in CSS by converting them to data URIs. ptachoire/cssembed scans your stylesheets for url(...) references and replaces eligible assets with base64-encoded content, reducing HTTP requests and simplifying distribution of self-contained CSS.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require ptachoire/cssembed
    

    Add the service provider to config/app.php under providers:

    Ptachoire\CssEmbed\CssEmbedServiceProvider::class,
    
  2. Basic Usage Embed CSS URLs in a Blade template:

    use Ptachoire\CssEmbed\CssEmbed;
    
    // In a controller or service
    $cssEmbed = app(CssEmbed::class);
    $embeddedCss = $cssEmbed->embed('path/to/your/styles.css');
    echo $embeddedCss;
    
  3. First Use Case Replace external CSS URLs in Blade views with embedded versions:

    <link href="{{ $cssEmbed->embed('css/main.css') }}" rel="stylesheet">
    

    Ensure the cssembed middleware is registered in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \Ptachoire\CssEmbed\Middleware\CssEmbedMiddleware::class,
    ];
    

Implementation Patterns

Workflows

  1. Embedding CSS in Controllers

    public function show()
    {
        $cssEmbed = app(CssEmbed::class);
        $embeddedStyles = $cssEmbed->embedMultiple([
            'css/main.css',
            'css/theme.css'
        ]);
        return view('home', ['styles' => $embeddedStyles]);
    }
    
  2. Blade Directives Create a custom Blade directive for seamless embedding:

    // In AppServiceProvider@boot()
    Blade::directive('embedCss', function ($expression) {
        return "<?php echo app(\Ptachoire\CssEmbed\CssEmbed::class)->embed({$expression}); ?>";
    });
    

    Usage:

    <link href="{{ embedCss('css/main.css') }}" rel="stylesheet">
    
  3. Middleware Integration Automatically embed CSS for specific routes:

    Route::middleware(['cssembed'])->group(function () {
        Route::get('/dashboard', 'DashboardController@index');
    });
    

Integration Tips

  • Asset Optimization: Combine with Laravel Mix or Vite for minification before embedding.
  • Caching: Cache embedded CSS responses to avoid reprocessing:
    $embeddedCss = Cache::remember('embedded_css_main', now()->addDays(7), function () {
        return $cssEmbed->embed('css/main.css');
    });
    
  • Dynamic Paths: Use route parameters for dynamic CSS paths:
    $cssEmbed->embed("css/themes/{$theme}.css");
    

Gotchas and Tips

Pitfalls

  1. Relative Paths Ensure CSS files referenced in @import or url() within your CSS use absolute paths (e.g., /images/logo.png) or configure the package to resolve them:

    $cssEmbed->setBaseUrl('/public');
    
  2. Large Files Embedding very large CSS files may increase response size. Consider:

    • Splitting CSS into smaller files.
    • Using the package’s embedMultiple with chunking.
  3. Middleware Order Place CssEmbedMiddleware after ShareErrorsFromSession and StartSession in Kernel.php to avoid embedding issues with session-based paths.

Debugging

  • Log Embedded Content: Temporarily log the embedded CSS to debug:
    \Log::debug('Embedded CSS:', ['content' => $embeddedCss]);
    
  • Check File Existence: Verify CSS files exist at the expected paths:
    if (!file_exists(public_path('css/main.css'))) {
        throw new \Exception('CSS file not found');
    }
    

Config Quirks

  • Custom Directories: Override the default storage directory for embedded CSS:
    $cssEmbed->setStoragePath(storage_path('app/embedded_css'));
    
  • Excluded Files: Skip embedding for specific files:
    $cssEmbed->exclude(['css/vendor.css', 'css/print.css']);
    

Extension Points

  1. Custom Embedders Extend the CssEmbedder interface to support additional formats (e.g., SCSS):

    class ScssEmbedder implements CssEmbedder {
        public function embed(string $path): string {
            // Custom SCSS processing logic
        }
    }
    

    Register it in the service provider:

    $this->app->bind(CssEmbedder::class, ScssEmbedder::class);
    
  2. Pre/Post Processing Hook into the embedding process via events (if the package supports them) or wrap the embedder:

    $embeddedCss = $cssEmbed->embed('css/main.css');
    $processedCss = str_replace('/* old comment */', '', $embeddedCss);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui