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

imanghafoori/laravel-nullable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require imanghafoori/laravel-nullable
    

    No publisher or service provider needed—automatically registered via package discovery.

  2. First Use Case: Replace null checks with expressive Nullable methods. Example:

    use Imanghafoori\Nullable\Nullable;
    
    $value = Nullable::from($user->profile)->get('email');
    // Equivalent to: $user->profile ? $user->profile->email : null
    
  3. Key Entry Points:

    • Nullable::from($value) – Wrap any value (objects, arrays, scalars).
    • Chain methods like get(), when(), or(), or tap() for functional workflows.

Implementation Patterns

Core Workflows

  1. Defensive Data Access:

    $user = User::find(1);
    $email = Nullable::from($user)
        ->get('profile.email') // Nested access
        ->or('default@example.com'); // Fallback
    
  2. Conditional Logic:

    Nullable::from($request->input('active'))
        ->when(true, fn() => $this->activateUser())
        ->when(false, fn() => $this->deactivateUser());
    
  3. Collection/Array Handling:

    $prices = Nullable::from($products)
        ->map(fn($p) => $p['price'])
        ->filter(fn($p) => $p > 100)
        ->toArray();
    
  4. Integration with Eloquent:

    $user = User::whereHas('nullable->profile', fn($q) => $q->where('active', true))->get();
    // Uses `nullable` global helper for query scopes.
    

Advanced Patterns

  • Custom Fallbacks:
    $value = Nullable::from($user->settings)
        ->get('theme')
        ->or(fn() => Theme::default());
    
  • Tap for Side Effects:
    Nullable::from($order->items)
        ->tap(fn($items) => $this->logItems($items))
        ->sum('price');
    
  • Validation Shortcuts:
    $input = Nullable::from($request->all())
        ->validate(['email' => 'required|email']);
    

Gotchas and Tips

Pitfalls

  1. Overuse of get():

    • Avoid deep chaining (e.g., get('a.b.c.d'))—use intermediate variables for readability.
    • Example:
      // Bad
      Nullable::from($user)->get('profile.address.city');
      
      // Good
      $city = Nullable::from($user)->get('profile.address')->get('city');
      
  2. Performance with Large Collections:

    • Methods like filter() or map() create new collections. Use toArray() early if memory is a concern.
  3. Global Helper Conflicts:

    • The nullable() helper may clash with Laravel’s nullable() cast. Explicitly use Imanghafoori\Nullable\Nullable to avoid ambiguity.

Debugging Tips

  • Null Checks: Use ->isNull() or ->isNotNull() for explicit debugging:

    if (Nullable::from($value)->isNull()) {
        logger()->debug('Value was null');
    }
    
  • Method Chaining: If a chain fails silently, add ->then(fn($v) => logger()->debug($v)) to inspect intermediate values.

Extension Points

  1. Custom Methods: Extend the Nullable class by creating a trait or subclass:

    use Imanghafoori\Nullable\Nullable;
    
    class ExtendedNullable extends Nullable {
        public function isEmpty(): bool {
            return $this->value === null || ($this->value instanceof Collection && $this->value->isEmpty());
        }
    }
    
  2. Query Builder Integration: Override the nullable global helper in your AppServiceProvider:

    use Imanghafoori\Nullable\Facades\Nullable;
    
    Nullable::extend('custom', function ($query, $relation) {
        return $query->whereHas($relation, fn($q) => $q->where('custom_field', '>', 0));
    });
    
  3. Testing: Mock Nullable in tests using partial mocks:

    $nullable = $this->partialMock(Nullable::class, ['get']);
    $nullable->method('get')->willReturn('mocked_value');
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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