Handling Laravel Collection first() with Strict Return Types

πŸ“– 1 minute read

When using Laravel collections with strict return types, be careful with first() – it returns null when the collection is empty, which can cause TypeErrors with strict return type declarations.

The Problem

public function getDefault(): ConfigInterface
{
    return $this->filter(fn ($config) => $config instanceof DefaultConfig)->first();
}

If the filtered collection is empty, first() returns null, but the method signature promises ConfigInterface. PHP 8+ strict types will throw a TypeError.

Solution Options

1. Nullable return type (safest)

public function getDefault(): ?ConfigInterface
{
    return $this->filter(fn ($config) => $config instanceof DefaultConfig)->first();
}

2. Throw exception (fail-fast)

public function getDefault(): ConfigInterface
{
    $config = $this->filter(fn ($config) => $config instanceof DefaultConfig)->first();
    
    if ($config === null) {
        throw new \RuntimeException('No default config found');
    }
    
    return $config;
}

3. Provide default value

public function getDefault(): ConfigInterface
{
    return $this->filter(fn ($config) => $config instanceof DefaultConfig)
                ->first() ?? new NullConfig();
}

Choose based on your use case:

  • Nullable for optional values
  • Exception for required values
  • Default object for null object pattern

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *