Skip to content

Conversation

@mvpopuk
Copy link

@mvpopuk mvpopuk commented Nov 21, 2025

Purpose

Adds unlessEmpty() and unlessNotEmpty() methods to Stringable to bring it to API parity with Collection, which already has these methods.

Current State

Collection has:

  • unless($value, $callback, $default) (via Conditionable trait)
  • unlessEmpty($callback, $default)
  • unlessNotEmpty($callback, $default)

Stringable has:

  • unless($value, $callback, $default) (via Conditionable trait)
  • unlessEmpty($callback, $default) - MISSING
  • unlessNotEmpty($callback, $default) - MISSING

This PR adds the missing two methods to complete the API symmetry.

Changes

  • Added unlessEmpty($callback, $default) method to Stringable
  • Added unlessNotEmpty($callback, $default) method to Stringable
  • Added comprehensive tests for both methods

Example Usage

Before:

// Awkward - checking if empty
Str::of($input)->unless($input === '', fn($s) => $s->append('suffix'))

// Double negation
Str::of($input)->unless(! $input, fn($s) => $s->upper())

After

// Clean and expressive
Str::of($input)->unlessEmpty(fn($s) => $s->append('suffix'))

Str::of($input)->unlessNotEmpty(fn($s) => $s->upper())

Real-world example

// Apply formatting unless string is empty
$name = Str::of($userInput)
    ->trim()
    ->unlessEmpty(fn($s) => $s->title())
    ->unlessEmpty(fn($s) => $s->append('.'), fn($s) => $s->append('N/A')); 

Benefits

  • API consistency: Matches Collection's unlessEmpty and unlessNotEmpty methods
  • Better readability: More expressive than unless(empty()) or unless(! empty())
  • Completes the API: Stringable already has whenEmpty and whenNotEmpty, now has the unless variants
  • Follows Laravel patterns: Collection has had these methods for years

Backwards Compatibility

  • Fully backwards compatible - pure addition with no breaking changes.

Related

  • Collection has had unlessEmpty and unlessNotEmpty since Laravel 5.x
  • Stringable already has unless() via Conditionable trait
  • Stringable already has whenEmpty() and whenNotEmpty()
  • This completes the conditional API symmetry

@taylorotwell
Copy link
Member

I frankly find these methods so hard to even parse in my brain 😅 let's just recommend people use whenEmpty and whenNotEmpty. The double negative of unlessNotEmpty is really hard to read imo and I don't want to encourage it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants