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

Bdf Prime Laravel Package

b2pweb/bdf-prime

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require b2pweb/bdf-prime
    

    Add to config/app.php under providers:

    B2PWeb\BDFPrime\PrimeServiceProvider::class,
    
  2. Basic Model Definition Define a model extending B2PWeb\BDFPrime\Model:

    namespace App\Models;
    
    use B2PWeb\BDFPrime\Model;
    
    class User extends Model
    {
        protected $table = 'users';
        protected $primaryKey = 'id';
        protected $fillable = ['name', 'email'];
    }
    
  3. First Query

    $users = User::all(); // Returns collection
    $user = User::find(1); // Single record
    
  4. Configuration Check config/prime.php for default settings (e.g., connection, caching). Override via:

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST'),
        ],
    ],
    

Implementation Patterns

Core Workflows

  1. CRUD Operations

    // Create
    $user = User::create(['name' => 'John', 'email' => 'john@example.com']);
    
    // Update
    $user->update(['name' => 'Updated Name']);
    
    // Delete
    User::destroy(1); // Single
    User::where('active', false)->delete(); // Bulk
    
  2. Query Building

    // Chaining
    $activeUsers = User::where('active', true)
                        ->orderBy('name')
                        ->limit(10)
                        ->get();
    
    // Dynamic Conditions
    $query = User::query();
    if ($request->has('search')) {
        $query->where('name', 'like', '%'.$request->search.'%');
    }
    
  3. Relationships Define in model:

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
    

    Eager load:

    $usersWithPosts = User::with('posts')->get();
    
  4. Events & Hooks Override lifecycle methods:

    protected static function boot()
    {
        parent::boot();
    
        static::creating(function ($model) {
            $model->created_at = now();
        });
    }
    
  5. Transactions

    DB::transaction(function () {
        User::create(['name' => 'Alice']);
        Post::create(['user_id' => 1, 'title' => 'Hello']);
    });
    

Integration Tips

  1. Laravel Ecosystem

    • Works seamlessly with Laravel’s DB facade for raw queries.
    • Use Prime::table() for dynamic table names:
      $results = Prime::table('custom_table')->get();
      
  2. API Resources Pair with Laravel’s API Resources for structured responses:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'posts_count' => $this->posts()->count(),
        ];
    }
    
  3. Testing Use Prime::fake() for mocking:

    public function test_user_creation()
    {
        Prime::fake();
        $user = User::create(['name' => 'Test']);
        $this->assertDatabaseHas('users', ['name' => 'Test']);
    }
    
  4. Caching Enable query caching in config/prime.php:

    'cache' => [
        'enabled' => true,
        'driver' => 'file',
    ],
    

Gotchas and Tips

Pitfalls

  1. Primary Key Assumptions

    • Defaults to id; explicitly define $primaryKey if using custom keys (e.g., uuid).
  2. Mass Assignment

    • Always define $fillable or $guarded to avoid mass assignment vulnerabilities.
    • Example:
      protected $guarded = ['password_hash']; // Guard specific fields
      
  3. Connection Switching

    • If using multiple databases, specify the connection in queries:
      User::on('mysql_secondary')->get();
      
    • Ensure config/prime.php lists all connections.
  4. Timestamps

    • Disabled by default. Enable with:
      public $timestamps = true;
      
    • Or customize:
      const CREATED_AT = 'created_on';
      const UPDATED_AT = 'updated_on';
      
  5. Soft Deletes

    • Requires explicit setup:
      use B2PWeb\BDFPrime\SoftDeletes;
      
      class User extends Model
      {
          use SoftDeletes;
          protected $dates = ['deleted_at'];
      }
      
    • Use withTrashed() to include soft-deleted records.

Debugging

  1. Query Logging Enable in config/prime.php:

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

    Or log manually:

    Prime::enableQueryLog();
    $users = User::all();
    dd(Prime::getQueryLog());
    
  2. Common Errors

    • Column Not Found: Verify table/column names match the database.
    • Foreign Key Errors: Use onDelete('cascade') in migrations or handle manually.
    • Serialization Issues: Ensure model attributes are JSON-serializable (avoid closures/objects in $fillable).
  3. Performance

    • N+1 Problem: Always use with() for eager loading.
    • Indexing: Add indexes to frequently queried columns (e.g., email).

Extension Points

  1. Custom Accessors/Mutators

    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }
    
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
    
  2. Scopes

    public function scopeActive($query)
    {
        return $query->where('active', true);
    }
    

    Usage:

    $activeUsers = User::active()->get();
    
  3. Observers

    class UserObserver
    {
        public function saving(User $user)
        {
            $user->updated_at = now();
        }
    }
    

    Register in AppServiceProvider:

    User::observe(UserObserver::class);
    
  4. Macros Add global query methods:

    Prime::macro('findByEmail', function ($email) {
        return $this->where('email', $email)->first();
    });
    

    Usage:

    $user = User::findByEmail('test@example.com');
    
  5. Events Listen to model events:

    User::created(function ($user) {
        // Send welcome email
    });
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager