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

Result Type Laravel Package

graham-campbell/result-type

Lightweight PHP Result type implementation for explicit success/failure returns. Provides Ok/Err-style results to avoid exceptions and clarify control flow. Compatible with PHP 7.2.5–8.5; install via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer: composer require graham-campbell/result-type. Begin by importing the core types: use GrahamCampbell\ResultType\Result; use GrahamCampbell\ResultType\Ok; use GrahamCampbell\ResultType\Err;. A first practical use case is wrapping fallible operations where exceptions feel too heavy—e.g., validating DTOs, parsing external data, or handling HTTP client responses—returning Result<mixed, string> to make success/failure explicit.

// Wrap a potentially failing operation
$validated = Result::tryFrom(
    fn() => $this->validateEmail($input),
    'Invalid email format'
);

Check the README and run composer test on the source to see minimal, self-contained examples.

Implementation Patterns

Use Result at boundaries—not deep inside business logic—to explicit error handling without disrupting Laravel’s exception-driven core. Common patterns:

  • Validation/DTO layer: Return Result<ValidatedData, string[]> from form/DTO validators instead of throwing exceptions or returning null.
  • Service composition: Chain operations with then() (monadic bind) to short-circuit on errors:
    Result::tryFrom(fn() => $this->fetchRemoteData($id))
        ->then(fn($data) => Result::tryFrom(fn() => $this->parseData($data), 'Parse failed')))
        ->mapOk(fn($parsed) => $this->saveToDb($parsed));
    
  • HTTP response mapping: In controllers, convert Result to responses early:
    $result = $service->processOrder($request);
    return $result->match(
        fn($order) => response()->json($order),
        fn($error) => response()->json(['error' => $error], 400)
    );
    
  • Fallback handling: Use valueOr() for defaults or mapErr() to coerce domain errors into user-friendly messages.

Prefer match() over isErr()/value() for exhaustive pattern-matching—ensures both branches are handled.

Gotchas and Tips

  • No destructuring in PHP: Unlike Rust, you must explicitly handle both Ok/Err using match() or check via isOk()/isErr() before calling value()/error(). Unhandled Err causes runtime failures if unwrapped carelessly.
  • Avoid overuse: Don’t wrap every method—Result shines for external interactions (APIs, files, networks), not pure PHP logic (e.g., arithmetic). Excessive wrapping increases cognitive load with little benefit.
  • PHP version quirks: While the package supports PHP 7.2.5+, use docblocks for union returns in older versions (@return Result<int, string>), as Ok|Err type-hinting requires PHP 8+.
  • No semantic equality: new Ok(1) === new Ok(1) is false. Compare inner values via $result->value() when testing equality.
  • Laravel compatibility: Laravel expects exceptions (Eloquent, validation, middleware). Use Result within service layers, then convert to exceptions or HTTP responses at the edge—avoid mixing styles in the same call stack.
  • Debugging tip: Leverage tap() to inspect values mid-chain without disrupting flow:
    $result->tap(fn($v) => logger()->debug('Processing value', ['v' => $v]))
           ->mapOk(...);
    
  • Testing: Mock external calls before wrapping with Result::tryFrom()—test Result consumers by asserting against Ok/Err branches, not exceptions.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport