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

Db Blade Compiler Laravel Package

flynsarmy/db-blade-compiler

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require flynsarmy/db-blade-compiler
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Flynsarmy\DbBladeCompiler\DbBladeCompilerServiceProvider" --tag="config"
    
  2. Basic Usage Define a Blade template in a model field (e.g., description in a Post model):

    // Migration
    Schema::table('posts', function (Blueprint $table) {
        $table->text('description')->nullable();
    });
    

    Store Blade syntax in the field:

    <h1>{{ $title }}</h1>
    <p>Published on {{ $created_at->format('M d, Y') }}</p>
    
  3. Compile and Render Use the renderBlade() method on the model:

    $post = Post::find(1);
    $rendered = $post->renderBlade('description', [
        'title' => 'My Awesome Post',
    ]);
    echo $rendered;
    
  4. View the Source Check the config file for default settings (e.g., cache_path, view_paths).


Implementation Patterns

1. Dynamic Blade Rendering in Models

Use renderBlade() to dynamically render fields with data from other fields or external sources:

$post = Post::find(1);
$html = $post->renderBlade('content', [
    'author' => $post->user->name,
    'tags' => $post->tags->pluck('name'),
]);

2. Reusable Templates Across Models

Store common Blade snippets in a dedicated table (e.g., template_snippets) and reference them via IDs:

// Migration
Schema::create('template_snippets', function (Blueprint $table) {
    $table->id();
    $table->text('blade_content');
    $table->string('name');
});

// Usage
$snippet = TemplateSnippet::where('name', 'user_card')->first();
$userHtml = $user->renderBladeFromString($snippet->blade_content, ['user' => $user]);

3. Caching Compiled Views

Enable caching in config/db-blade-compiler.php:

'cache' => [
    'enabled' => true,
    'path' => storage_path('framework/views'),
],

Clear cache when templates change:

php artisan view:clear

4. Integration with API Responses

Return rendered Blade as part of API responses:

return response()->json([
    'post' => [
        'title' => $post->title,
        'rendered_content' => $post->renderBlade('content'),
    ],
]);

5. Conditional Rendering

Use Blade conditionals to toggle content:

@if($is_premium)
    <div class="premium-badge">⭐ Premium Content</div>
@endif

6. Extending with Directives

Create custom Blade directives for reusable logic:

// In a service provider
Blade::directive('formatDate', function ($expression) {
    return "<?php echo ($expression)->format('F j, Y'); ?>";
});

// Usage in DB field
<p>Created: @formatDate($created_at)</p>

Gotchas and Tips

Pitfalls

  1. Cache Invalidation

    • Forgetting to clear the view cache (php artisan view:clear) after updating Blade templates in the DB.
    • Fix: Automate cache clearing via model observers or events.
  2. Variable Scope Leaks

    • Accidentally exposing sensitive data in Blade variables passed to renderBlade().
    • Fix: Sanitize inputs and use strict variable whitelisting.
  3. Performance Overhead

    • Rendering large Blade templates on every request without caching.
    • Fix: Cache rendered output at the model level or use Laravel’s remember() method.
  4. SQL Injection Risks

    • Storing raw Blade with unescaped user input (e.g., {{ $user_input }}).
    • Fix: Escape dynamic content with |e or {{ __($var) }}.
  5. Missing Dependencies

    • Forgetting to pass required variables to the Blade template.
    • Fix: Validate required variables in a model accessor:
      public function getRenderedDescriptionAttribute()
      {
          return $this->renderBlade('description', [
              'title' => $this->title ?? 'Untitled',
          ]);
      }
      

Debugging Tips

  • Check Compiled Output: Enable Blade debugging in config/app.php:

    'debug' => env('APP_DEBUG', true),
    

    View compiled views in storage/framework/views.

  • Log Errors: Wrap renderBlade() calls in try-catch:

    try {
        $html = $model->renderBlade('field');
    } catch (\Exception $e) {
        Log::error("Blade render failed: " . $e->getMessage());
        $html = '<p class="error">Failed to render content.</p>';
    }
    
  • Test Locally: Use tinker to test Blade rendering:

    php artisan tinker
    >>> $post = App\Models\Post::find(1);
    >>> $post->renderBlade('description', ['title' => 'Test']);
    

Extension Points

  1. Custom Storage Engines Override the Flynsarmy\DbBladeCompiler\Engines\EngineResolver to support non-DB storage (e.g., Redis, S3).

  2. Blade Extensions Register custom Blade components/directives in a service provider:

    Blade::component('alert', AlertComponent::class);
    
  3. Model Observers Automatically render fields on save:

    class PostObserver
    {
        public function saved(Post $post)
        {
            $post->renderBlade('teaser', ['title' => $post->title])->save();
        }
    }
    
  4. API for Template Management Build a CRUD interface for managing Blade templates in the DB via Laravel Nova or Filament.

  5. Fallback Content Provide default Blade templates if a field is empty:

    $html = $post->renderBlade('description', [
        'title' => $post->title,
    ], '<p>No description available.</p>');
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours