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 Boolean Dates Laravel Package

sebastiaanluca/laravel-boolean-dates

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sebastiaanluca/laravel-boolean-dates
    

    Publish the config (optional, but recommended for customization):

    php artisan vendor:publish --provider="SebastiaanLuca\BooleanDates\BooleanDatesServiceProvider"
    
  2. Model Configuration: Add the BooleanDates trait to your Eloquent model:

    use SebastiaanLuca\BooleanDates\BooleanDates;
    
    class User extends Model
    {
        use BooleanDates;
    
        protected $booleanDates = [
            'has_accepted_terms' => 'accepted_terms_at',
            'is_subscribed_to_newsletter' => 'subscribed_at',
        ];
    
  3. First Use Case: After saving a model with a boolean field (has_accepted_terms = true), access the dynamic date property:

    $user = User::create(['has_accepted_terms' => true]);
    $user->accepted_terms_at; // Returns Carbon instance
    

Implementation Patterns

Core Workflows

  1. Form Handling:

    • Accept boolean inputs (e.g., checkboxes) in controllers:
      $user->update(['has_accepted_terms' => $request->has('terms')]);
      
    • Automatically populate the corresponding date field (accepted_terms_at).
  2. Dynamic Property Access:

    • Use the generated date properties in views or logic:
      if ($user->accepted_terms_at) {
          echo "Accepted on: " . $user->accepted_terms_at->format('Y-m-d');
      }
      
  3. Mass Assignment:

    • Exclude dynamic date fields from mass assignment in $fillable to avoid conflicts:
      protected $fillable = ['has_accepted_terms', /* ... */];
      
  4. API Responses:

    • Serialize both boolean and date fields in API responses:
      return UserResource::make($user)->additional([
          'accepted_terms_at' => $user->accepted_terms_at,
      ]);
      

Integration Tips

  • Validation: Use Laravel’s validation rules to ensure boolean fields are validated before conversion:

    $request->validate(['terms' => 'accepted']);
    
  • Database Schema: Add the corresponding date columns to your migration:

    $table->boolean('has_accepted_terms')->default(false);
    $table->timestamp('accepted_terms_at')->nullable();
    
  • Query Scopes: Filter models by date ranges:

    public function scopeAcceptedAfter($query, $date)
    {
        return $query->where('accepted_terms_at', '>=', $date);
    }
    
  • Events/Observers: Trigger logic when boolean fields change (e.g., send emails on acceptance):

    public function updatedHasAcceptedTerms(User $user)
    {
        if ($user->wasChanged('has_accepted_terms') && $user->has_accepted_terms) {
            Mail::to($user)->send(new TermsAccepted($user));
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Circular References:

    • Avoid referencing the dynamic date property in $fillable or $guarded; it’s auto-generated and shouldn’t be manually managed.
  2. Null Handling:

    • If a boolean field is null, the dynamic date property will also be null. Ensure your logic handles this edge case:
      $user->accepted_terms_at ?? 'Never accepted';
      
  3. Timestamp Precision:

    • The package uses Carbon for date handling. If your database uses a different timezone, ensure consistency in your config/app.php:
      'timezone' => 'UTC',
      
  4. Model Caching:

    • Dynamic properties may not reflect changes if the model is cached. Use fresh() or refresh() to reload data:
      $user->fresh()->accepted_terms_at;
      

Debugging

  • Check Config: Verify the $booleanDates array in your model maps correctly to database columns:

    protected $booleanDates = [
        'has_accepted_terms' => 'accepted_terms_at', // Must match DB column
    ];
    
  • Log Conversions: Enable debug logging to trace conversions:

    \Log::debug('Boolean to date conversion:', [
        'boolean' => $user->has_accepted_terms,
        'date' => $user->accepted_terms_at,
    ]);
    

Extension Points

  1. Custom Date Formatting: Override the default Carbon instance by extending the trait:

    use SebastiaanLuca\BooleanDates\BooleanDates as BaseBooleanDates;
    
    class User extends Model
    {
        use BaseBooleanDates;
    
        public function getAcceptedTermsAtAttribute()
        {
            return $this->booleanDatesGet('has_accepted_terms')
                ? Carbon::now()->startOfDay()
                : null;
        }
    
  2. Batch Processing: Use the package’s BooleanDates facade for bulk operations (if added in future updates):

    \SebastiaanLuca\BooleanDates\Facades\BooleanDates::convert($model);
    
  3. Soft Deletes: Ensure soft-deleted models don’t interfere with date conversions by excluding them from queries or handling them in observers:

    if ($user->trashed()) {
        $user->accepted_terms_at = null;
    }
    
  4. Testing: Mock dynamic properties in tests:

    $user = User::factory()->create(['has_accepted_terms' => true]);
    $this->assertInstanceOf(Carbon::class, $user->accepted_terms_at);
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle