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

Model Shared Laravel Package

inisiatif/model-shared

Kumpulan model Eloquent bersama untuk Inisiatif Zakat Indonesia: pekerjaan, tingkat pendidikan, wilayah (negara–provinsi–desa), dan status perkawinan. Mendukung relasi dinamis Branch dan Employee pada model Donor via resolveRelationUsing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Run composer require inisiatif/model-shared in your Laravel project. Ensure your composer.json specifies Laravel 10+ compatibility if needed (check release notes).

  2. Publish Migrations Execute php artisan vendor:publish --provider="Inisiatif\ModelShared\ModelSharedServiceProvider" to publish migrations for all shared models (e.g., degrees, regions, donors). Run migrations with php artisan migrate.

  3. First Use Case: Donor Model Use the Donor model directly in your controllers:

    use Inisiatif\ModelShared\Models\Donor;
    
    $donor = Donor::create([
        'name' => 'John Doe',
        'email' => 'john@example.com', // Added in v2.10.1
        'phone_id' => '12345',        // Added in v2.10.2
        'degree_id' => 1,
        'marital_status_id' => 1,
    ]);
    
  4. Dynamic Relations (Critical for Integration) Configure dynamic relations in your AppServiceProvider’s boot() method (as shown in the README). Example:

    Donor::resolveRelationUsing('branch', fn(Donor $donor) => $donor->belongsTo(\App\Models\Branch::class, 'branch_id'));
    
  5. Seed Reference Data (Optional) Use the package’s seeders (if provided) or manually seed degrees, regions, and other reference tables via php artisan db:seed --class=ModelSharedSeeder.


Implementation Patterns

Core Workflows

1. Geographic Data Integration

  • Hierarchical Queries: Leverage the nested Region models (e.g., Province, District, Village) for location-based filtering:
    $village = \Inisiatif\ModelShared\Models\Village::with('district.region.province')->find($id);
    
  • Search API: Use the region-search API (added in v2.5.0) for autocomplete or bulk lookups:
    $regions = \Inisiatif\ModelShared\Http\Controllers\RegionSearchController::search('Jakarta');
    

2. Donor Management

  • Lifecycle Hooks: Extend the Donor model for custom logic (e.g., notifications):
    use Inisiatif\ModelShared\Models\Donor;
    
    class CustomDonor extends Donor {
        protected static function booted() {
            static::created(fn($donor) => notify($donor)->via('email')->send(new DonorRegistered()));
        }
    }
    
  • Dynamic Relations: Dynamically attach relations to Donor (e.g., branch, employee) as shown in the README. Example for a custom Employee relation:
    Donor::resolveRelationUsing('employee', fn(Donor $donor) =>
        $donor->belongsTo(\App\Models\Employee::class, 'employee_id')
    );
    

3. Financial Workflows

  • Outflows Tracking: Use the Outflow model (added in v2.9.0) to log disbursements:
    $outflow = \Inisiatif\ModelShared\Models\Outflow::create([
        'donor_id' => $donor->id,
        'amount' => 1000000,
        'category_id' => 1, // e.g., 'Food'
        'status' => 'pending',
    ]);
    
  • Donations: Link donations to donors via Donation and DonationDetail (added in v2.7.3):
    $donation = \Inisiatif\ModelShared\Models\Donation::create([
        'donor_id' => $donor->id,
        'amount' => 500000,
        'type_id' => 1, // e.g., 'Cash'
    ]);
    

4. Reference Data

  • Education Levels: Use the Degree model for standardized education fields:
    $degree = \Inisiatif\ModelShared\Models\Degree::where('name', 'SMA')->first();
    
  • Marital Status: Query the MaritalStatus model:
    $status = \Inisiatif\ModelShared\Models\MaritalStatus::where('name', 'Menikah')->first();
    

Integration Tips

Laravel Ecosystem

  • Service Providers: Register the package’s service provider in config/app.php under providers:
    Inisiatif\ModelShared\ModelSharedServiceProvider::class,
    
  • Config Publishing: Publish configs (if any) with:
    php artisan vendor:publish --tag=model-shared-config
    
  • API Resources: Extend the package’s API resources (e.g., DonorResource) in your app/Http/Resources:
    namespace App\Http\Resources;
    
    use Inisiatif\ModelShared\Http\Resources\DonorResource as BaseDonorResource;
    
    class DonorResource extends BaseDonorResource {
        public function toArray($request) {
            $array = parent::toArray($request);
            $array['custom_field'] = $this->customField;
            return $array;
        }
    }
    

Testing

  • Unit Tests: Mock dynamic relations in tests:
    $donor = new Donor();
    $donor->newQuery()->shouldReceive('belongsTo')
        ->with(\App\Models\Branch::class, 'branch_id')
        ->andReturn(new BelongsTo());
    
  • Feature Tests: Test geographic hierarchies:
    $village = \Inisiatif\ModelShared\Models\Village::factory()->create();
    $this->assertEquals($village->district->region->name, 'DKI Jakarta');
    

Performance

  • Eager Loading: Always eager-load nested relations (e.g., with('district.region')) to avoid N+1 queries.
  • Caching: Cache reference data (e.g., Degree, MaritalStatus) in AppServiceProvider:
    Cache::remember('degrees', now()->addHours(1), fn() =>
        \Inisiatif\ModelShared\Models\Degree::all()
    );
    

Gotchas and Tips

Pitfalls

  1. Dynamic Relations Overhead

    • Issue: Dynamic relations (e.g., Donor::branch) are resolved at runtime, which can impact performance if overused.
    • Fix: Use them sparingly. For frequently accessed relations, define them directly in your Donor model:
      public function branch() {
          return $this->belongsTo(\App\Models\Branch::class, 'branch_id');
      }
      
  2. Migration Conflicts

    • Issue: The package’s migrations may conflict with existing tables (e.g., donors, regions) if your project already has them.
    • Fix: Check the package’s migrations before publishing. Rename or merge tables manually if needed.
  3. UUID vs. Increment ID

    • Issue: Some models (e.g., Partner in v2.8.2) use UUIDs, while others use auto-increment IDs. This can cause issues in polymorphic relations or foreign key constraints.
    • Fix: Ensure your custom models align with the package’s ID strategy. Use morphMap if mixing UUIDs and increments:
      class Donor extends Model {
          public function getMorphClass() {
              return 'donor';
          }
      }
      
  4. Deprecated or Typo Fixes

    • Issue: Some releases (e.g., v2.9.1) fix typos in migration filenames (e.g., accountaccounts). Older versions may have broken migrations.
    • Fix: Always pull the latest version and check the changelog for fixes.
  5. Laravel Version Compatibility

    • Issue: The package’s last release (2026) may not support Laravel 11+. Check composer.json for Laravel constraints.
    • Fix: Test thoroughly or fork the package to update dependencies.

Debugging

  1. Dynamic Relation Errors

    • Symptom: Call to undefined method when accessing dynamic relations (e.g., Donor::branch).
    • Debug: Verify the relation is registered in AppServiceProvider::boot():
      Donor::resolveRelationUsing('branch', fn($donor) => $donor->belongsTo(\App\Models\Branch::class, 'branch_id'));
      
    • Tip: Use dd($donor->getRelation('branch')) to inspect the relation.
  2. Geographic Data Inconsistencies

    • **Sympt
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