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

Laravel Attributes Laravel Package

rinvex/laravel-attributes

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require rinvex/laravel-attributes
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Rinvex\Attributes\AttributesServiceProvider"
    php artisan migrate
    
  2. Define an Attribute Group In your model (e.g., User.php), declare attributes:

    use Rinvex\Attributes\Traits\HasAttributes;
    
    class User extends Model
    {
        use HasAttributes;
    
        protected $attributes = [
            'personal' => [
                'name' => 'string',
                'age'  => 'integer',
            ],
            'contact' => [
                'email' => 'string',
                'phone' => 'string',
            ],
        ];
    
  3. First Use Case: Set/Get Attributes

    $user = new User();
    $user->setAttribute('personal.name', 'John Doe'); // Set
    $user->getAttribute('personal.name'); // Get
    

Implementation Patterns

Core Workflows

  1. Dynamic Attribute Management Use setAttribute() and getAttribute() for runtime flexibility:

    $user->setAttribute('contact.email', 'john@example.com');
    $user->getAttribute('contact.email');
    
  2. Validation Leverage Laravel’s validation rules via validateAttribute():

    $user->validateAttribute('contact.email', 'required|email');
    
  3. Querying Attributes Use whereAttribute() for EAV queries:

    User::whereAttribute('personal.age', '>', 25)->get();
    
  4. Attribute Groups as Relations Access groups like relations:

    $user->personal; // Returns a collection of attributes
    $user->contact->phone; // Dot notation
    
  5. Mass Assignment Use fillAttributes() for bulk updates:

    $user->fillAttributes([
        'personal.name' => 'Jane Doe',
        'personal.age'   => 30,
    ]);
    

Integration Tips

  • Caching: Cache attribute groups for performance:
    $user->cacheAttributes(['personal', 'contact']);
    
  • Events: Listen to attributes.storing and attributes.retrieved:
    event(new \Rinvex\Attributes\Events\AttributeStored($user, 'personal.name'));
    
  • APIs: Serialize attributes with toArray() or toJson():
    $user->toArray(); // Includes attributes
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • If using an existing EAV table, manually adjust the attributes table schema to match the package’s expectations (e.g., entity_type, group, name, value columns).
  2. Caching Quirks

    • Clearing cached attributes requires explicit calls:
      $user->forgetAttribute('personal.name');
      $user->forgetAttributes(['personal', 'contact']);
      
  3. Case Sensitivity

    • Attribute names (group.name) are case-sensitive. Use consistent casing (e.g., snake_case).
  4. Mass Assignment Risks

    • Always validate before fillAttributes() to avoid injection:
      $user->fillAttributes($request->only(['personal.*']));
      
  5. Performance with Large Datasets

    • Avoid whereAttribute() on non-indexed columns. Add indexes to group and name in the attributes table:
      Schema::table('attributes', function (Blueprint $table) {
          $table->index(['entity_type', 'group', 'name']);
      });
      

Debugging

  • Dump Attributes Use dd($user->attributes) to inspect raw EAV data.
  • Query Logging Enable Laravel’s query logging to debug whereAttribute():
    \DB::enableQueryLog();
    User::whereAttribute('personal.age', '>', 25)->get();
    \DB::getQueryLog();
    

Extension Points

  1. Custom Attribute Types Extend Rinvex\Attributes\Contracts\Attribute for custom logic (e.g., encrypted values):

    class EncryptedAttribute implements Attribute
    {
        public function get($model, $value)
        {
            return decrypt($value);
        }
    }
    
  2. Override Default Behavior Replace the trait in your model:

    use Rinvex\Attributes\Traits\HasAttributes as BaseHasAttributes;
    
    class User extends Model
    {
        use BaseHasAttributes {
            BaseHasAttributes::getAttribute as private getAttributeBase;
        }
    
        public function getAttribute($name)
        {
            // Custom logic
            return $this->getAttributeBase($name);
        }
    }
    
  3. Add Global Scopes Attach scopes to filter attributes globally:

    use Rinvex\Attributes\Scopes\AttributeScope;
    
    class User extends Model
    {
        protected static function booted()
        {
            static::addGlobalScope(new AttributeScope(['personal.age >', 25]));
        }
    }
    
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.
besmartand-pro/php-quality-config
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