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

Bauhausblock Laravel Package

krafthaus/bauhausblock

Laravel package for building “Bauhaus” content blocks/components for your app or CMS. Provides a structured way to define, render, and manage reusable blocks, helping you compose pages from modular content with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require krafthaus/bauhausblock
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Krafthaus\Bauhausblock\BauhausblockServiceProvider"
    
  2. Basic Usage:

    • Define a block in a migration:
      use Krafthaus\Bauhausblock\Block;
      
      Schema::create('blocks', function (Blueprint $table) {
          $table->block('hero_section', Block::class);
      });
      
    • Create a block model (optional but recommended):
      php artisan make:model Block/HeroSection
      
    • Use the block in a view:
      @block('hero_section')
      
  3. First Use Case:

    • Render a block dynamically in a Blade template:
      @block('hero_section', ['title' => 'Welcome', 'content' => 'This is a hero section'])
      
    • Fetch a block by ID:
      $block = \Krafthaus\Bauhausblock\Facades\Bauhausblock::find(1);
      

Implementation Patterns

Core Workflows

  1. Block Definition:

    • Define blocks in migrations using block() method:
      $table->block('sidebar', Block::class, ['default' => ['title' => 'Default']]);
      
    • Use traits for reusable block logic:
      use Krafthaus\Bauhausblock\Traits\HasBlocks;
      
  2. Block Management:

    • Create/Update:
      $block = \Krafthaus\Bauhausblock\Facades\Bauhausblock::create('hero_section', [
          'title' => 'New Hero',
          'content' => 'Updated content'
      ]);
      
    • Fetching:
      // By name
      $blocks = \Krafthaus\Bauhausblock\Facades\Bauhausblock::get('hero_section');
      
      // By ID
      $block = \Krafthaus\Bauhausblock\Facades\Bauhausblock::find(1);
      
  3. View Integration:

    • Dynamic Rendering:
      @block('hero_section', ['title' => 'Dynamic Title'])
      
    • Conditional Rendering:
      @if($block = \Krafthaus\Bauhausblock\Facades\Bauhausblock::find(1))
          @block('hero_section', $block->data)
      @endif
      
  4. API Endpoints:

    • Use Laravel's API resources to expose blocks:
      Route::get('/blocks/{block}', [BlockController::class, 'show']);
      
    • Example controller:
      public function show($blockName)
      {
          return \Krafthaus\Bauhausblock\Facades\Bauhausblock::get($blockName);
      }
      

Integration Tips

  • Caching: Cache block queries for performance:
    $blocks = Cache::remember("blocks_{$blockName}", now()->addHours(1), function () use ($blockName) {
        return \Krafthaus\Bauhausblock\Facades\Bauhausblock::get($blockName);
    });
    
  • Events: Listen for block creation/update events:
    \Krafthaus\Bauhausblock\Events\BlockUpdated::class => [BlockObserver::class, 'handleUpdate']
    
  • Validation: Validate block data using Form Requests:
    public function rules()
    {
        return [
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ];
    }
    

Gotchas and Tips

Common Pitfalls

  1. Migration Conflicts:

    • Ensure block migrations are run after the main blocks table migration.
    • Avoid renaming block types after initial setup (data loss risk).
  2. Data Serialization:

    • Block data is stored as JSON. Ensure your data is JSON-serializable:
      // Bad: Non-serializable (e.g., DateTime objects)
      $block = ['date' => new DateTime()];
      
      // Good: Convert to string or array
      $block = ['date' => (new DateTime())->format('Y-m-d')];
      
  3. Facade vs. Direct Usage:

    • Prefer the facade (\Krafthaus\Bauhausblock\Facades\Bauhausblock) for simplicity, but inject the service container binding (\Krafthaus\Bauhausblock\Bauhausblock) for testing or complex logic.
  4. Default Values:

    • Default values in migrations are not merged with runtime updates. Override them explicitly:
      $block = \Krafthaus\Bauhausblock\Facades\Bauhausblock::create('hero_section', [
          'title' => 'Override Default',
          'content' => 'New content'
      ]);
      

Debugging Tips

  1. Query Logs:

    • Enable Laravel's query logging to debug block queries:
      \DB::enableQueryLog();
      $blocks = \Krafthaus\Bauhausblock\Facades\Bauhausblock::get('hero_section');
      dd(\DB::getQueryLog());
      
  2. Block Existence:

    • Check if a block type exists before querying:
      if (\Krafthaus\Bauhausblock\Facades\Bauhausblock::hasType('hero_section')) {
          $blocks = \Krafthaus\Bauhausblock\Facades\Bauhausblock::get('hero_section');
      }
      
  3. Data Corruption:

    • If block data appears corrupted (e.g., malformed JSON), manually inspect the data column in the database and repair:
      $block = \App\Models\Block::find(1);
      $block->data = json_decode($block->data, true);
      $block->save();
      

Extension Points

  1. Custom Block Types:

    • Extend the base Block class for type-specific logic:
      class HeroSection extends \Krafthaus\Bauhausblock\Block
      {
          public function getTitle()
          {
              return $this->data['title'] ?? 'Default Title';
          }
      }
      
    • Register the custom type in the config:
      'types' => [
          'hero_section' => \App\Models\HeroSection::class,
      ],
      
  2. Block Events:

    • Extend the event system for custom logic:
      \Krafthaus\Bauhausblock\Events\BlockCreated::class => function ($event) {
          // Send notification or log creation
      };
      
  3. Query Scoping:

    • Add global scopes to filter blocks:
      use Illuminate\Database\Eloquent\Scope;
      
      class ActiveScope implements Scope
      {
          public function apply(Builder $builder, Model $model)
          {
              $builder->whereJsonContains('data->active', true);
          }
      }
      
    • Register the scope in the Block model:
      protected static function booted()
      {
          static::addGlobalScope(new ActiveScope);
      }
      
  4. Block Storage:

    • Override the storage engine (e.g., Redis) by binding the Bauhausblock interface:
      $this->app->bind(\Krafthaus\Bauhausblock\Contracts\BlockRepository::class, \App\Services\RedisBlockRepository::class);
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle