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 Casters Laravel Package

rawilk/laravel-casters

Collection of custom Eloquent cast classes for Laravel models. Add handy casts like Name to normalize and manipulate attributes automatically. Install via Composer; full docs available online.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require rawilk/laravel-casters
    

    Ensure your composer.json lists Laravel 11+ and PHP 8.2+ (check releases).

  2. First Use Case: Apply the Name cast to a model’s name attribute for automatic formatting (e.g., title case, trimming):

    use Rawilk\LaravelCasters\Casts\Name;
    
    class User extends Model
    {
        protected $casts = [
            'name' => Name::class,
        ];
    }
    

    Now, $user->name = ' john doe ' will auto-trim and title-case to "John Doe" when accessed.

  3. Key Entry Points:


Implementation Patterns

Core Workflows

  1. Attribute Casting:

    • Standard Usage:
      protected $casts = [
          'email' => Email::class,       // Validates and normalizes emails
          'slug'  => Slug::class,        // Generates URL-friendly slugs
          'tags'  => Tags::class,        // Handles comma-separated tags
          'active' => Boolean::class,    // Ensures boolean storage (e.g., `1`/`0` → `true`/`false`)
      ];
      
    • Dynamic Casting: Use getCasts() to conditionally apply casts:
      public function getCasts()
      {
          return array_merge(parent::getCasts(), [
              'formatted_address' => $this->shouldFormatAddress() ? Address::class : 'string',
          ]);
      }
      
  2. Customizing Casts:

    • Extend Existing Casts:
      use Rawilk\LaravelCasters\Casts\Name;
      
      class CustomName extends Name
      {
          protected $format = 'UPPER'; // Override default formatting
      }
      
    • Create New Casts: Implement Illuminate\Contracts\Database\Eloquent\CastsAttributes:
      use Rawilk\LaravelCasters\Casts\Cast;
      
      class CustomCast extends Cast
      {
          public function get($model, string $key, $value, array $attributes)
          {
              return strtoupper($value);
          }
      
          public function set($model, string $key, $value, array $attributes)
          {
              return strtolower($value);
          }
      }
      
  3. Model-Specific Patterns:

    • Single Name Column: Use the HasSingleNameColumn contract for models with a single name field:
      use Rawilk\LaravelCasters\Contracts\HasSingleNameColumn;
      
      class Product extends Model implements HasSingleNameColumn
      {
          // ...
      }
      
      This ensures proper serialization of the name attribute.
  4. API Responses:

    • Leverage casts in toArray() or toJson() for consistent formatting:
      public function toArray()
      {
          return [
              'name' => $this->name, // Automatically cast via $casts
              'created_at' => $this->created_at->format('Y-m-d'),
          ];
      }
      
  5. Form Requests:

    • Cast input data before validation:
      use Rawilk\LaravelCasters\Casts\Email;
      
      public function rules()
      {
          return [
              'email' => ['required', new Email], // Custom cast as a validator
          ];
      }
      

Integration Tips

  1. Database Schema:

    • Casts like Boolean or Tags may require specific column types (e.g., TEXT for tags, TINYINT for booleans).
  2. Testing:

    • Test casts in isolation:
      public function test_name_cast()
      {
          $user = new User(['name' => '  jane doe  ']);
          $this->assertEquals('Jane Doe', $user->name);
      }
      
    • Use Model::newFromBuilder() to test cast hydration:
      $model = User::newFromBuilder([
          'name' => '  john doe  ',
      ]);
      $this->assertEquals('John Doe', $model->name);
      
  3. Performance:

    • Avoid overusing casts in loops or complex queries. Casts are applied per-attribute access.
    • For bulk operations, consider pre-processing data before casting (e.g., array_map on collections).
  4. Laravel Ecosystem:

    • Scout: Casts like Slug integrate seamlessly with Laravel Scout for searchable slugs.
    • Nova/Livewire: Casts ensure consistent data display in admin panels or UI components.

Gotchas and Tips

Pitfalls

  1. Database Writes:

    • Name Cast: Avoid storing computed values (e.g., slugs derived from name) directly to the database. The Name cast in v3.0.3+ prevents this, but ensure your migrations don’t duplicate logic.
    • Boolean Cast: Laravel stores 1/0 for booleans by default. If your database uses TRUE/FALSE, explicitly set:
      protected $casts = [
          'is_active' => Boolean::class,
      ];
      protected $attributes = [
          'is_active' => 0, // Default to FALSE
      ];
      
  2. Null Handling:

    • Some casts (e.g., Email) may throw exceptions on null values. Use nullable() in your $casts array:
      protected $casts = [
          'optional_email' => [Email::class, 'nullable'],
      ];
      
  3. Version Mismatches:

    • Laravel 13+: Uses PHP 8.5 features. Avoid mixing with older Laravel versions.
    • Deprecated Casts: The Password cast was removed in v4.0.0. Use Laravel’s native hash cast instead:
      protected $casts = [
          'password' => 'hash',
      ];
      
  4. Serialization:

    • Casts are not applied during array:where or cursor queries. Use getAttributes() or fresh() to re-cast:
      $user = User::where('name', 'like', '%john%')->first();
      $user->name; // May not be cast if fetched via cursor
      $user->fresh()->name; // Re-casts
      

Debugging

  1. Cast Order:

    • Casts run in the order defined in $casts. Override getCasts() if order matters:
      public function getCasts()
      {
          return ['slug' => Slug::class, 'name' => Name::class]; // Slug cast runs first
      }
      
  2. Custom Cast Logging:

    • Add debug logs to custom casts:
      public function get($model, string $key, $value, array $attributes)
      {
          Log::debug("Casting {$key}: {$value}");
          return strtoupper($value);
      }
      
  3. Common Issues:

    • "Cast does not exist": Ensure the cast class is fully qualified (e.g., Rawilk\LaravelCasters\Casts\Name).
    • Performance: Use tap() to inspect cast behavior:
      $user->name->tap(fn($name) => Log::debug("Cast result: {$name}"));
      

Extension Points

  1. Custom Cast Attributes:

    • Pass options to casts via array syntax:
      protected $casts = [
          'name' => [Name::class, 'format' => 'UPPER'],
      ];
      
    • Access options in your cast’s constructor:
      public function __construct(array $options = [])
      {
          $this->format = $options['format'] ?? 'title';
      }
      
  2. Global Casts:

    • Register casts globally in AppServiceProvider:
      use Rawilk\LaravelCasters\Casts\Email;
      
      public function boot()
      {
          \Illuminate\Database\Eloquent\Casts\Cast::macro('email', function () {
              return Email::class;
          });
      }
      
      Now use shorthand:
      protected $casts = [
          'email' => 'email',
      ];
      
  3. Testing Custom Casts:

    • Mock casts in tests:
      $cast = Mockery::mock(Rawilk\LaravelCasters\Casts\Name::class);
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle