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

Redbean Laravel Package

gabordemooij/redbean

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require gabordemooij/redbean
    

    Add to config/app.php under providers:

    RedBeanPHP\Laravel\RedBeanServiceProvider::class,
    
  2. Basic Configuration: In config/redbean.php (auto-generated), set your database connection:

    'connection' => 'mysql', // or 'pgsql', 'sqlite'
    
  3. First Use Case:

    use RedBeanPHP\R;
    
    // Initialize RedBean
    R::setup('mysql:host=localhost;dbname=test', 'username', 'password');
    
    // Create a simple model (Eloquent or plain PHP object)
    $user = new \App\Models\User; // Eloquent model
    $user->name = 'John Doe';
    R::store($user); // Works with Simple Models
    
    // Tag a model
    R::tag($user, 'admin');
    $admins = R::findTagged('admin', 'App\Models\User');
    

Where to Look First


Implementation Patterns

Core Workflows

1. Tagging Models (Primary Use Case)

// Tag an Eloquent model
$user = User::find(1);
R::tag($user, 'premium', 'vip'); // Multiple tags

// Find tagged models
$premiumUsers = R::findTagged('premium', User::class);

// Count tagged items
$count = R::countTagged('premium');

2. Hybrid ORM Usage (Eloquent + RedBean)

// Use Eloquent for core logic, RedBean for tags
$user = User::find(1); // Eloquent
R::tag($user, 'active'); // RedBean tagging

// Query with tags
$activeUsers = R::findTagged('active', User::class)->get();

3. Schema-Less Flexibility

// Dynamically add fields to a model
$post = new Post();
$post->title = 'Dynamic Post';
$post->custom_field = 'value'; // No schema needed
R::store($post);

4. Transactions with Laravel

DB::transaction(function () {
    $order = Order::create(['user_id' => 1, 'amount' => 100]);
    R::tag($order, 'pending');
});

Integration Tips

  1. Laravel Service Provider: Override RedBean’s default behavior in RedBeanServiceProvider:

    public function boot()
    {
        R::setEnforceUTF8Encoding(true);
        R::setAllowFluidTransactions(true); // Laravel-style transactions
    }
    
  2. Eloquent Model Hooks: Use model events to sync RedBean tags:

    // app/Models/User.php
    protected static function booted()
    {
        static::saved(function ($user) {
            if ($user->wasRecentlyCreated) {
                R::tag($user, 'new_user');
            }
        });
    }
    
  3. Query Builder Integration: Combine Laravel’s query builder with RedBean:

    $users = User::whereHas('posts', function ($q) {
        $q->where('published', true);
    })->get();
    
    // Tag all published users
    foreach ($users as $user) {
        R::tag($user, 'published_author');
    }
    
  4. Caching Tags: Cache frequent tag queries:

    $cachedTags = Cache::remember('premium_users', now()->addHours(1), function () {
        return R::findTagged('premium', User::class)->pluck('id');
    });
    

Gotchas and Tips

Pitfalls

  1. Simple Model Limitations:

    • No automatic relationship loading: Unlike Eloquent, RedBean doesn’t auto-load relationships. Use R::load() or R::loadJoined() explicitly.

      // ❌ Won't work as expected
      $user = User::find(1);
      $user->posts; // May return null
      
      // ✅ Correct
      $user = R::load('user', 1);
      $posts = R::findJoined('post', 'user_id = ?', [$user->id]);
      
    • Mass Assignment Risks: Simple Models bypass Eloquent’s $fillable. Sanitize inputs:

      $user = new User();
      $user->name = request()->input('name'); // Unsafe!
      R::store($user);
      
  2. Transaction Quirks:

    • RedBean’s R::transaction() doesn’t play well with Laravel’s DB::transaction(). Use Laravel’s transactions for consistency:
      // ❌ Avoid mixing
      DB::transaction(function () {
          R::store($user); // May cause issues
      });
      
      // ✅ Preferred
      R::setAllowFluidTransactions(true); // Then use R::transaction()
      
  3. Tagging Edge Cases:

    • Case Sensitivity: Tags are case-sensitive by default. Normalize tags:
      R::tag($user, strtolower('Premium')); // Store as 'premium'
      
    • Tag Limits: RedBean doesn’t enforce tag limits. Monitor database size for large tag sets.
  4. Hybrid Mode Confusion:

    • If using both Eloquent and RedBean for the same model, avoid:
      // ❌ Double-save issues
      $user = User::find(1);
      $user->name = 'Updated';
      $user->save(); // Eloquent
      R::store($user); // RedBean (may cause conflicts)
      
    • Solution: Stick to one ORM per model or use RedBean only for tags.

Debugging Tips

  1. Enable Debug Logging:

    R::debug(true); // Logs all SQL queries to Laravel logs
    
  2. Check for Frozen Beans: RedBean freezes beans after first load. Unfreeze if needed:

    $user = R::load('user', 1);
    R::unfreeze($user); // Allows modifications
    
  3. PHP 8.5+ Gotchas:

    • Named Arguments: RedBean’s older methods may not support PHP 8.5’s named args. Use positional args:
      // ✅ Preferred
      R::tag($user, 'admin');
      
      // ❌ May fail in PHP 8.5+
      R::tag(user: $user, tag: 'admin');
      
  4. Performance Bottlenecks:

    • N+1 Queries: Use R::loadJoined() or R::findWith() for related data:
      $users = R::findWith('user', 'posts', 'user_id = ?', [1]);
      
    • Tag Queries: Cache R::findTagged() results aggressively.

Extension Points

  1. Custom Tag Handlers: Extend tag behavior via plugins:

    R::addPlugin('tag', function ($bean, $tags) {
        // Custom logic before tagging
        return $tags;
    });
    
  2. Override Model Behavior: Use R::setModel() to customize Simple Model handling:

    R::setModel('user', [
        'name' => 'App\Models\User',
        'extra' => function ($bean) {
            $bean->customMethod = function () { return 'Hello'; };
        }
    ]);
    
  3. DDL Templates: Customize schema generation:

    R::setDDLTemplate('user', [
        'id' => 'INTEGER PRIMARY KEY AUTO_INCREMENT',
        'name' => 'VARCHAR(255) NOT NULL',
        'custom_field' => 'TEXT'
    ]);
    
  4. Event Listeners: Hook into RedBean’s lifecycle:

    R::addEventListener('beforeStore', function ($bean) {
        if ($bean instanceof User) {
            $bean->created_at = now();
        }
    });
    

Laravel-Specific Quirks

  1. Service Container Binding: Bind RedBean’s R facade to Laravel’s container:

    $this->app->singleton('RedBeanPHP\R', function ($app) {
        $r = new \RedBeanPHP\R();
        $r->setWriteAheadLogging(true);
        return $r;
    });
    
  2. Migration Conflicts: RedBean’s schema-less approach may conflict with Laravel migrations. Use:

    R::
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky