PHPackages                             phpattempt/phpattempt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. phpattempt/phpattempt

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

phpattempt/phpattempt
=====================

Helper function to enforce error-first approach in your code

v1.0.2(1y ago)1710.4k↓12.1%1[1 issues](https://github.com/phpattempt/phpattempt/issues)MITPHPPHP ^8.2.0

Since Mar 23Pushed 1y ago1 watchersCompare

[ Source](https://github.com/phpattempt/phpattempt)[ Packagist](https://packagist.org/packages/phpattempt/phpattempt)[ RSS](/packages/phpattempt-phpattempt/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

PHPAttempt 🛡️
=============

[](#phpattempt-️)

A minimalistic PHP package that encourages error-first programming approach, helping you write more reliable and maintainable code.

[![PHP Version](https://camo.githubusercontent.com/7982862155fb0056accb2824ca092e5aafdf6cde6aa4982abcfe824ae5777f55/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f706870617474656d70742f706870617474656d70742e7376673f763d31)](https://packagist.org/packages/phpattempt/phpattempt)[![Latest Version on Packagist](https://camo.githubusercontent.com/9becdf1fd496a0145071ffa3552457dfd4deebfe198eaa9b5b864096d76dcdd4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f706870617474656d70742f706870617474656d70742e7376673f763d31)](https://packagist.org/packages/phpattempt/phpattempt)

Installation
------------

[](#installation)

```
composer require phpattempt/phpattempt
```

Usage
-----

[](#usage)

The attempt() function takes a callable and returns an array containing the result and any potential error:

```
[$data, $error] = attempt(fn () => someRiskyOperation());

if ($error) {
    // Handle error
    log($error->getMessage());
    return;
}

// Process $data safely
echo $data;
```

Why Use PHPAttempt?
-------------------

[](#why-use-phpattempt)

- 🎯 Error-First Mindset : Forces developers to consider error cases first
- 🧩 Clean Code : Reduces try-catch block nesting and improves readability
- 🔒 Type-Safe : Fully typed return values for better IDE support
- 🪶 Lightweight : Zero dependencies, just one function
- ⚡ Framework Agnostic : Works with any PHP project

Requirements
------------

[](#requirements)

- PHP 8.2 or higher

Basic Examples
--------------

[](#basic-examples)

```
// Simple calculation
[$result, $error] = attempt(fn () => 1 + 1);
// $result = 2, $error = null

// Handling potential errors
[$user, $error] = attempt(function () {
    if (!validateInput()) {
        throw new InvalidArgumentException('Invalid input');
    }
    return createUser();
});

if ($error) {
    return response()->json(['error' => $error->getMessage()], 400);
}
```

Usage with Laravel example
--------------------------

[](#usage-with-laravel-example)

```
// Controller method
public function store(Request $request)
{
    [$user, $error] = attempt(function () use ($request) {
        return User::create($request->validated());
    });

    if ($error) {
        return back()->withErrors(['message' => $error->getMessage()]);
    }

    return redirect()->route('users.show', $user);
}

// Service layer
public function processPayment(Order $order)
{
    [$transaction, $error] = attempt(function () use ($order) {
        $payment = StripePayment::create([
            'amount' => $order->total,
            'currency' => 'usd',
        ]);

        return $order->transactions()->create([
            'payment_id' => $payment->id,
            'status' => 'completed'
        ]);
    });

    if ($error) {
        Log::error('Payment failed: ' . $error->getMessage());
        throw new PaymentFailedException($error->getMessage());
    }

    return $transaction;
}
```

Nested Attempts
---------------

[](#nested-attempts)

You can safely nest attempt() calls:

```
[$result, $error] = attempt(function () {
    [$user, $userError] = attempt(fn () => User::findOrFail($id));

    if ($userError) {
        throw new UserNotFoundException($userError->getMessage());
    }

    [$order, $orderError] = attempt(fn () => $user->orders()->latest()->firstOrFail());

    if ($orderError) {
        throw new OrderNotFoundException($orderError->getMessage());
    }

    return ['user' => $user, 'last_order' => $order];
});
```

License
-------

[](#license)

The MIT License (MIT). Please see License File for more information.

Credits
-------

[](#credits)

[webpnk.dev](https://webpnk.dev)

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance44

Moderate activity, may be stable

Popularity35

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

421d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/54d8801bfdb83eca95e66a3200b9251962c8589e71887b9041198ea869fc36e6?d=identicon)[webpnk](/maintainers/webpnk)

---

Top Contributors

[![webpnk](https://avatars.githubusercontent.com/u/93125849?v=4)](https://github.com/webpnk "webpnk (8 commits)")

---

Tags

phpexceptionerror

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/phpattempt-phpattempt/health.svg)

```
[![Health](https://phpackages.com/badges/phpattempt-phpattempt/health.svg)](https://phpackages.com/packages/phpattempt-phpattempt)
```

###  Alternatives

[justbetter/magento2-sentry

Magento 2 Logger for Sentry

1851.5M3](/packages/justbetter-magento2-sentry)[thehocinesaad/laravel-error-ai

This package adds Ask AI button to the error page.

2214.4k](/packages/thehocinesaad-laravel-error-ai)[e2ex/e2ex

Converts PHP Errors to Exceptions and (optionally) logs PHP Errors, Notices and Warnings with a PSR-3 compatible logger

101.5k](/packages/e2ex-e2ex)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
