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

Eloquence Mappable Laravel Package

sofa/eloquence-mappable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sofa/eloquence-mappable
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Sofa\Eloquence\EloquenceServiceProvider"
    
  2. Enable Mappable: Extend your Eloquent model with Sofa\Eloquence\Mappable\MappableTrait:

    use Sofa\Eloquence\Mappable\MappableTrait;
    
    class User extends Model
    {
        use MappableTrait;
    }
    
  3. First Use Case: Define a mapping in your model:

    protected $mappable = [
        'full_name' => 'name', // Maps 'full_name' to 'name' field
        'email_address' => 'email',
        'user_profile' => ['profile_id' => 'profile.id'], // Maps to related model
    ];
    

    Use it to map an array:

    $mappedData = User::map(['full_name' => 'John Doe', 'email_address' => 'john@example.com']);
    $user = User::create($mappedData);
    

Implementation Patterns

Core Workflows

  1. Basic Attribute Mapping:

    // Map incoming data to model attributes
    $data = ['first_name' => 'Jane', 'last_name' => 'Doe'];
    $mapped = User::map($data, ['full_name' => 'first_name last_name']);
    
  2. Related Model Mapping:

    // Map nested data to related models (e.g., Profile)
    $mappable = [
        'user_profile' => [
            'bio' => 'bio',
            'avatar' => 'avatar_url',
        ],
    ];
    
  3. Dynamic Mapping: Use map() in controllers or services:

    public function store(Request $request)
    {
        $validated = $request->validate([...]);
        $user = User::map($validated)->create();
    }
    
  4. Bulk Mapping:

    $users = collect([...])->map(fn($data) => User::map($data)->create());
    

Integration Tips

  • APIs: Use map() in API requests to transform incoming JSON into model attributes.
  • Forms: Map form submissions directly to model fields.
  • Imports: Process CSV/Excel data with map() before saving records.
  • Caching: Cache mapped data if transformations are expensive:
    $mapped = Cache::remember("user_{$id}_mapped", now()->addHours(1), fn() => User::find($id)->map($data));
    

Gotchas and Tips

Pitfalls

  1. Circular References: Avoid circular mappings (e.g., A maps to B, B maps back to A). Use explicit ignore in $mappable:

    protected $mappableIgnore = ['related_model'];
    
  2. Overwriting Mutators: If your model has custom accessors/mutators, ensure they don’t conflict with map() logic. Override map() if needed:

    public function map(array $data, array $mappable = null)
    {
        $data = parent::map($data, $mappable);
        // Custom logic here
        return $data;
    }
    
  3. Mass Assignment: map() does not automatically whitelist fields for fillable. Explicitly define $fillable or use guarded.

  4. Performance: Deeply nested mappings (e.g., 3+ levels) can slow queries. Optimize with eager loading:

    User::with('profile')->map($data);
    

Debugging

  • Check Mappings: Log the resolved mappings to debug:
    dd(User::getMappable($data));
    
  • Validation Errors: If map() fails silently, enable debug mode or check for missing keys in $mappable.

Extension Points

  1. Custom Mappers: Extend the mapper class:

    class CustomMapper extends \Sofa\Eloquence\Mappable\Mapper
    {
        protected function transform($key, $value) { ... }
    }
    

    Bind it in AppServiceProvider:

    Eloquence::extend('custom', function () {
        return new CustomMapper();
    });
    
  2. Dynamic Mappings: Use closures for runtime mappings:

    protected $mappable = [
        'dynamic_field' => function ($value) {
            return strtoupper($value);
        },
    ];
    
  3. Event Hooks: Listen to eloquence.mapping events for logging/auditing:

    Event::listen('eloquence.mapping', function ($model, $data, $mapped) {
        // Log or audit changes
    });
    

Config Quirks

  • Default Mapper: Override the default mapper in config/eloquence.php:
    'mapper' => \App\CustomMapper::class,
    
  • Strict Mode: Enable strict mode to throw errors on missing keys:
    User::map($data, null, ['strict' => true]);
    
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.
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament