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

Eloquent Model Laravel Package

supportpal/eloquent-model

Eloquent-style base Model for PHP/Laravel to build custom, non-database models. Supports accessors/mutators, attribute casting, guarded/fillable and hidden fields, appended attributes, and easy array/JSON conversion.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require jenssegers/model
    

    Add the namespace to your composer.json under autoload.psr-4:

    "Jenssegers\Model": "vendor/jenssegers/model/src"
    
  2. Basic Model Setup: Extend Jenssegers\Model\Model in your custom model:

    use Jenssegers\Model\Model;
    
    class User extends Model
    {
        protected $fillable = ['name', 'email'];
    }
    
  3. First Use Case: Instantiate and populate a model:

    $user = new User(['name' => 'John Doe', 'email' => 'john@example.com']);
    $user->save(); // Override with custom logic (e.g., API call)
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Data Handling:

    • Fillable/Guarded: Restrict mass assignment:
      protected $fillable = ['name', 'email'];
      protected $guarded = ['password']; // Blocks unless in $fillable
      
    • Casting: Convert attributes on access:
      protected $casts = [
          'is_active' => 'boolean',
          'created_at' => 'datetime:Y-m-d'
      ];
      
  2. Custom Logic:

    • Override save() for non-DB storage (e.g., API calls):
      public function save()
      {
          $response = API::post('/users', $this->toArray());
          $this->id = $response['id'];
          return $this;
      }
      
    • Use accessors/mutators for derived data:
      public function getFullNameAttribute()
      {
          return "{$this->first_name} {$this->last_name}";
      }
      
  3. Serialization:

    • Control output with hidden/visible/appends:
      protected $hidden = ['password'];
      protected $appends = ['full_name'];
      

Integration Tips

  • Non-Laravel Frameworks: Replace Laravel’s API facade with your HTTP client (e.g., Guzzle).
  • Validation: Pair with a validator (e.g., Laravel’s Validator or Respect/Validation) before save().
  • Relationships: Implement manually (e.g., hasMany via array properties):
    public function orders()
    {
        return collect($this->orders)->map(fn($order) => new Order($order));
    }
    

Gotchas and Tips

Pitfalls

  1. No Database Abstraction:

    • Issue: The package lacks Eloquent’s query builder. Overriding save()/find() is manual.
    • Fix: Use a lightweight ORM (e.g., Cycle ORM) or raw PDO if needed.
  2. Attribute Casting Timing:

    • Issue: Casting happens on getAttribute(), not during initialization.
    • Fix: Cast manually in constructor if needed:
      public function __construct(array $attributes = [])
      {
          parent::__construct($attributes);
          $this->birthday = $this->asDateTime($this->birthday);
      }
      
  3. Hidden Attributes Leak:

    • Issue: hidden attributes may still appear in debug output (e.g., dd($model)).
    • Fix: Override toArray() to filter:
      public function toArray()
      {
          return array_diff_key($this->attributesToArray(), array_flip($this->hidden));
      }
      

Debugging

  • Check Attributes: Use getAttributes() to inspect raw data:
    dd($model->getAttributes());
    
  • Override toJson(): Add debug info:
    public function toJson($options = 0)
    {
        return json_encode([
            'data' => parent::toJson($options),
            'meta' => ['casts' => $this->casts]
        ], $options);
    }
    

Extension Points

  1. Custom Serialization: Extend toArray()/toJson() for nested structures:

    public function toArray()
    {
        return [
            'id' => $this->id,
            'metadata' => $this->getMetadataArray()
        ];
    }
    
  2. Event System: Add hooks (e.g., beforeSave):

    public function save()
    {
        $this->fireModelEvent('beforeSave');
        // ... custom logic ...
        $this->fireModelEvent('saved');
        return $this;
    }
    
  3. Macros: Dynamically add methods:

    Model::macro('replicateWithout', function ($attributes) {
        $model = clone $this;
        unset($model->{$attributes});
        return $model;
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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