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

Rowcast Laravel Package

ascetic-soft/rowcast

Lightweight PDO DataMapper for PHP 8.4+ that maps DB rows to DTOs and back via reflection. Supports auto or explicit mappings, type conversion, and a fluent query builder with dialect-aware UPSERT.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ascetic-soft/rowcast
    

    Add to config/app.php under providers:

    AsceticSoft\Rowcast\RowcastServiceProvider::class,
    
  2. Basic Usage Register a cast in AppServiceProvider:

    use AsceticSoft\Rowcast\Rowcast;
    
    public function boot()
    {
        Rowcast::macro('toArray', function ($value) {
            return json_decode($value, true);
        });
    }
    
  3. First Use Case Cast a JSON string to an array in a model attribute:

    use AsceticSoft\Rowcast\Rowcast;
    
    class Post extends Model
    {
        protected $casts = [
            'metadata' => Rowcast::toArray,
        ];
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Casting Useful for API responses or database fields:

    Rowcast::macro('toDateTime', function ($value) {
        return Carbon::parse($value);
    });
    
  2. Model Integration Apply casts in App\Models\Model for global reuse:

    class Model extends \Illuminate\Database\Eloquent\Model
    {
        protected $casts = [
            'created_at' => Rowcast::toDateTime,
            'updated_at' => Rowcast::toDateTime,
        ];
    }
    
  3. API Request Handling Cast incoming request data:

    use AsceticSoft\Rowcast\Rowcast;
    
    $request->merge([
        'tags' => Rowcast::toArray($request->tags),
    ]);
    

Integration Tips

  • Laravel Collections: Extend Illuminate\Support\Collection for batch casting:
    Collection::macro('cast', function ($macro) {
        return $this->map(fn ($item) => Rowcast::macro($macro, $item));
    });
    
  • Form Requests: Validate and cast in handle():
    $validated = $this->validate();
    $validated['config'] = Rowcast::toArray($validated['config']);
    

Gotchas and Tips

Pitfalls

  1. Macro Overrides Avoid naming conflicts with Laravel’s built-in casts (e.g., toArray). Fix: Use unique prefixes (e.g., rowcast_toArray).

  2. Null Handling Uncasted null values may break type checks. Fix: Add null checks in macros:

    Rowcast::macro('toArray', function ($value) {
        return $value ? json_decode($value, true) : [];
    });
    
  3. Performance Heavy casting in loops (e.g., Model::all()) can slow queries. Fix: Use selectRaw or cast in application logic.

Debugging

  • Macro Introspection List all registered macros:
    dd(Rowcast::getMacros());
    
  • Error Logging Wrap macros in try-catch for graceful failures:
    Rowcast::macro('toDateTime', function ($value) {
        try {
            return Carbon::parse($value);
        } catch (\Exception $e) {
            Log::error("Rowcast failed: {$e->getMessage()}");
            return null;
        }
    });
    

Extension Points

  1. Custom Cast Classes For reusable logic, create a trait:

    trait Castable
    {
        public static function castToArray($value) { ... }
    }
    

    Then use:

    Rowcast::macro('toArray', [Castable::class, 'castToArray']);
    
  2. Database-Level Casting Combine with Laravel’s $attributes for raw SQL casting:

    protected $attributes = [
        'metadata' => '{}', // Default empty array
    ];
    
  3. Testing Mock macros in PHPUnit:

    Rowcast::macro('toArray', fn ($x) => ['test']);
    $this->assertEquals(['test'], Rowcast::macro('toArray', '{}'));
    
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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver