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

prewk/result

prewk/result brings Rust-like Result to PHP: explicit Ok/Err values for safer, more readable error handling without exceptions. Use map/flatMap, unwrap/unwrapOr, and chain operations to handle success and failure paths cleanly in functional style.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require prewk/result
    

    The package is dependency-free and requires PHP 8.0+.

  2. Basic Usage Import the Result class and create instances:

    use Prewk\Result\Result;
    
    $success = Result::ok("Operation succeeded");
    $failure = Result::err(new \RuntimeException("Something went wrong"));
    
  3. First Use Case: Safe API Response Handling

    function fetchUser($id) {
        if ($user = User::find($id)) {
            return Result::ok($user);
        }
        return Result::err(new \InvalidArgumentException("User not found"));
    }
    
    $result = fetchUser(1);
    $result->match(
        fn($user) => "User: {$user->name}",
        fn($e) => "Error: {$e->getMessage()}"
    );
    

Implementation Patterns

Common Workflows

  1. Chaining Results (Flat Map) Transform a successful result into another operation:

    $result = fetchUser(1)
        ->flatMap(fn($user) => fetchPosts($user->id))
        ->map(fn($posts) => collect($posts)->pluck('title'));
    
  2. Error Handling with match()

    $result->match(
        fn($data) => response()->json($data),
        fn($e) => response()->json(['error' => $e->getMessage()], 400)
    );
    
  3. Validation Pipeline

    function validateInput(array $data): Result {
        return Result::ok($data)
            ->map(fn($d) => Validator::make($d, rules()))
            ->flatMap(fn($validator) => $validator->fails()
                ? Result::err(new \InvalidArgumentException($validator->errors()->first()))
                : Result::ok($validator->validated())
            );
    }
    

Integration with Laravel

  • Form Requests

    public function rules(): array {
        return ['email' => 'required|email'];
    }
    
    public function withValidator($validator) {
        if ($validator->fails()) {
            return Result::err(new \InvalidArgumentException($validator->errors()->first()));
        }
        return Result::ok($validator->validated());
    }
    
  • Service Layer

    class UserService {
        public function createUser(array $data): Result {
            return User::create($data)
                ? Result::ok($data)
                : Result::err(new \RuntimeException("Failed to create user"));
        }
    }
    
  • Middleware for API Errors

    public function handle($request, Closure $next) {
        $response = $next($request);
        if ($response->original instanceof Result && $response->original->isErr()) {
            return response()->json(['error' => $response->original->unwrapErr()->getMessage()], 400);
        }
        return $response;
    }
    

Gotchas and Tips

Pitfalls

  1. Unwrapping Errors Blindly

    // ❌ Dangerous: Throws exception if Result is Err
    $data = $result->unwrap(); // Avoid unless you're certain of success
    
    // ✅ Safer
    $data = $result->unwrapOr(null);
    
  2. Overusing match()

    • Prefer explicit isOk()/isErr() checks for complex logic to avoid nested callbacks.
  3. Performance with Heavy Operations

    • flatMap() chains operations eagerly. Use map() + unwrap() if lazy evaluation is needed.

Debugging

  • Inspecting Results

    $result->isOk();    // bool
    $result->isErr();   // bool
    $result->unwrap();  // throws on Err
    $result->unwrapErr();// throws on Ok
    
  • Logging Errors

    $result->match(
        fn($data) => log()->info("Success", ['data' => $data]),
        fn($e) => log()->error("Failed", ['error' => $e->getMessage()])
    );
    

Extension Points

  1. Custom Error Types

    class ValidationError extends \RuntimeException {}
    $result = Result::err(new ValidationError("Invalid data"));
    
  2. Result Decorators

    trait LoggableResult {
        public function tap(callable $callback): self {
            $this->match($callback, $callback);
            return $this;
        }
    }
    
  3. Laravel Collections Integration

    Result::ok($data)->then(fn($d) => collect($d)->keyBy('id'));
    

Config Quirks

  • No configuration file; behavior is purely runtime-based.
  • For global error handling, wrap Result::unwrap() calls in a helper:
    if (!$result->isOk()) {
        throw $result->unwrapErr();
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor