Table of Contents
π 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
Leave a Reply