PHPackages                             kirschbaum-development/laravel-actions - 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. kirschbaum-development/laravel-actions

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

kirschbaum-development/laravel-actions
======================================

A Laravel package for handling actions and events

v0.2.3(10mo ago)7166.1k↓20.4%1MITPHPPHP ^8.0CI passing

Since Feb 17Pushed 10mo ago14 watchersCompare

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

READMEChangelog (7)Dependencies (5)Versions (8)Used By (0)

Laravel Actions
===============

[](#laravel-actions)

### A package for handling simple actions with eventing.

[](#a-package-for-handling-simple-actions-with-eventing)

[![Latest Version on Packagist](https://camo.githubusercontent.com/87a02d432e71947c74e931fb250dfabff4275ca31c0c6e2024f1e679e1e26592/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b69727363686261756d2d646576656c6f706d656e742f6c61726176656c2d616374696f6e73)](https://packagist.org/packages/kirschbaum-development/laravel-actions)[![Total Downloads](https://camo.githubusercontent.com/8eb868f9f5828ade785b7ca67ab511a91acfa7666609908a3c4b6a098c6be180/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b69727363686261756d2d646576656c6f706d656e742f6c61726176656c2d616374696f6e73)](https://packagist.org/packages/kirschbaum-development/laravel-actions)[![Actions Status](https://github.com/kirschbaum-development/laravel-actions/workflows/CI/badge.svg)](https://github.com/kirschbaum-development/laravel-actions/actions)

Laravel Actions are simple job-like classes that don't interact with the queue. Actions are great to leverage when you have some simple functionality that you need to reuse.

But why would you want to use Actions you ask? Actions are great when you have small bits of code that you want to extract into small, testable classes. Actions can also take the place of queued jobs when you don't want or need that kind of power, or if you need the results of the code right now.

But the real power is with eventing.

This package exposes two events during your Action:

- Before the Action begins
- After the Action completes

The special sauce here is that you get to tell the Action which events you want triggered!

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

[](#requirements)

PHP VersionLaravel Actions Version`^6.0, ^7.0``^0.1.0``^8.0``^0.2.0`Installation
------------

[](#installation)

```
composer require kirschbaum-development/laravel-actions
```

Creating and Preparing the Action
---------------------------------

[](#creating-and-preparing-the-action)

Create a new Action with artisan command:

```
php artisan make:action ChuckNorris
```

This will create a new Action class at `app/Actions/ChuckNorris.php`. You are, of course, free to move the action wherever you want. Just make sure you update the namespace!

There are two public properties ready for your events: `$before` and `$after`. You can use one or both of these, and you can remove either of them if you don't use them in your Action class.

```
 /**
  * Event to dispatch before action starts.
  *
  * @var string
  */
 public $before = ChuckNorrisWillBlowYourMind::class;

 /**
  * Event to dispatch after action completes.
  *
  * @var string
  */
 public $after = ChuckNorrisBlewYourMind::class;
```

Next place your required arguments within the `__construct()` method and your Action code within the `__invoke()` method. You are free to return anything you might need from the invokeable method. Now we're ready to use the Action!

```
/**
 * Create a new action instance.
 *
 * @return void
 */
public function __construct()
{
    // Pass any arguments you need.
}

/**
 * Execute the action.
 *
 * @return mixed
 */
public function __invoke()
{
    // Handle your action here.
}
```

Usage
-----

[](#usage)

There are two different ways we can call our newly created Action.

### From the Action

[](#from-the-action)

We can call one of three methods on the Action itself as long as the class is using the `CanAct` trait.

```
ChuckNorris::act($data);
ChuckNorris::actWhen($isChuckNorrisMighty, $data);
ChuckNorris::actUnless($isChuckNorrisPuny, $data);
```

The `$data` is passed into the Action's constructor. You can pass as many arguments as needed in your use case.

The second two methods, `actWhen` and `actUnless` require a condition as the first variable. These work like other Laravel methods such as `throw_if()` and `throw_unless()`. Finally, you can pass as many arguments as needed for your Action after the condition.

### Facade

[](#facade)

The package also has a facade. Here's the syntax:

```
use Kirschbaum\Actions\Facades\Action;

Action::act(ChuckNorris::class, $data);
Action::actWhen($isChuckNorrisMighty, ChuckNorris::class, $data);
Action::actUnless($isChuckNorrisPuny, ChuckNorris::class, $data);
```

The usage is nearly identical to calling the methods directly on the Action as mentioned in the section above. The benefit here is that you can easily test actions using `Action::shouldReceive('act')`, `Action::shouldReceive('actWhen')` or `Action::shouldReceive('actUnless')`.

### Helpers

[](#helpers)

The package also has a few handy helpers to get Chuck in action. Here's the syntax:

```
act(ChuckNorris::class, $data);
act_when($isChuckNorrisMighty, ChuckNorris::class, $data);
act_unless($isChuckNorrisPuny, ChuckNorris::class, $data);
```

### Dependency Injection

[](#dependency-injection)

You can even inject Actions as a dependencies inside your application!

```
use Kirschbaum\Actions\Action;

public function index (Action $action)
{
    $action->act(ChuckNorris::class, $data);
    $action->actWhen($isChuckNorrisMighty, ChuckNorris::class, $data);
    $action->actUnless($isChuckNorrisPuny, ChuckNorris::class, $data);
}
```

Macros
------

[](#macros)

There are times when you may want to add something extra to your actions. We can leverage macros for this!

Here is an example were we are leveraging Inertia's defer functionality directly on our action. The macro then just calls `act()` on the action class when the deferred prop is requested!

```
// In your service provider
Action::macro('defer', function($action, ...$arguments) {
    return Inertia::defer(fn () => $action::act(...$arguments));
});

// In your controller
return Inertia::render('Users/Index')
    ->with('users', GetUsers::defer());
```

Note how the originating class is passed into the macro function as the first parameter. This is very important, otherwise the macro will be unaware of which action you are actually running as macros are technically run on the parent action class. You are also free to do what you want regarding the subsequent $arguments, but it is considered best practice to pack/unpack the arguments with the spread operator to ensure the actions are as flexible as possible.

Also take note the `defer()` is defined on the `Kirschbaum\Actions\Action` class, not on the `GetUsers` action class. Individual actions are not macroable in and of themselves. The macro `defer()` will also be available to every action in your application, not just the `GetUsers` action!

Before and after events will not be fired when using macros. They will get fired however if you use an action's `act()`, `actWhen()`, or `actUnless()` methods with the macro function.

Handling Failures
-----------------

[](#handling-failures)

We all know Chuck Norris isn't going to fail us, but he isn't the only one using this... Handling failures is pretty easy with Actions. Out of the box, any exceptions thrown by your Action classes get handled by Laravel's exception handler. If you'd rather implement your own logic during a failure, add a `failed()` method to your Action. It's that easy! You can return data from your `failed()` method if you choose as well.

```
/**
 * Handle failure of the action.
 *
 * @throws Throwable
 *
 * @return mixed
 */
public function failed(Throwable $exception)
{
    event(new VanDammeFailedEvent);
}
```

Hashtag #BAM!

### Custom Exceptions

[](#custom-exceptions)

Another option for handling failures is to tell the Action to throw its own exception. If you don't need the extra overhead of writing your own `failed()` method, you can just tell your Action to throw a custom exception. It's as simple as just defining the exception you want thrown from the Action.

```
/**
 * Event to dispatch if action throws an exception.
 *
 * @var string
 */
public $exception = SeagalFailedException::class;
```

Auto-Discovery and Configuration
--------------------------------

[](#auto-discovery-and-configuration)

Out of the box, actions are automatically discovered and bound to Laravel's container, which allows for easier testing of your actions. If you need to add a custom path if you are placing your actions somewhere other than `app/Actions`, make sure to publish the configs.

```
php artisan vendor:publish --tag laravel-actions
```

If you want to disable auto-discovery, publish the config and return an empty array from the `paths` key.

```
return [
    'paths' => [],
];
```

Testing
-------

[](#testing)

Have no fear. Testing all of this is very straightforward. There are two approaches to testing built in.

### Testing Facades

[](#testing-facades)

If you are using Facades to implement your Actions, you can use the standard `shouldReceive()` method directly from the Facade.

```
use Kirschbaum\Actions\Facades\Action;

Action::shouldReceive('act')
    ->once()
    ->andReturnTrue();
```

### Mocking

[](#mocking)

If you are using helpers, the `CanAct` trait, or dependency injection, you can easily mock the `Action` class with Laravel's mocking tools.

```
use Kirschbaum\Actions\Action;

$this->mock(Action::class, function ($mock) {
    $mock->shouldReceive('act')
        ->once()
        ->andReturnTrue();
});
```

Because actions are bound into Laravel's container by default, you can test specific actions as well.

```
use App\Actions\ChuckNorris;

$this->mock(ChuckNorris::class, function ($mock) {
    $mock->shouldReceive('act')
        ->once()
        ->andReturnTrue();
});
```

Last thoughts
-------------

[](#last-thoughts)

If for some reason you'd prefer not to use the cool Eventing system, Facades, Mocking, etc., that's fine. Just call your Action like this:

```
new ChuckNorris($data);
```

This will bypass all the magic and call the invoke method automagically, letting Chuck do his thing without anyone knowing, but why? ;)

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  or  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Brandon Ferens](https://github.com/brandonferens)
- Inspired in part by [Luke Downing's](https://github.com/lukeraymonddowning) Laracon Online Winter '22 [talk](https://www.youtube.com/watch?v=0Rq-yHAwYjQ&t=1678s).

Sponsorship
-----------

[](#sponsorship)

Development of this package is sponsored by Kirschbaum, a developer driven company focused on problem solving, team building, and community. Learn more [about us](https://kirschbaumdevelopment.com) or [join us](https://careers.kirschbaumdevelopment.com)!

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance54

Moderate activity, may be stable

Popularity37

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.7% 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 ~207 days

Recently: every ~310 days

Total

7

Last Release

305d ago

PHP version history (2 changes)v0.1.0PHP &gt;=7.2.5

v0.2.1PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/66b8ba124c4a8a7b5a6544665d0f7b48f78a3608e92b70ab03a7562a0a8dde07?d=identicon)[brandonferens](/maintainers/brandonferens)

---

Top Contributors

[![brandonferens](https://avatars.githubusercontent.com/u/1819546?v=4)](https://github.com/brandonferens "brandonferens (41 commits)")[![babacarcissedia](https://avatars.githubusercontent.com/u/17571380?v=4)](https://github.com/babacarcissedia "babacarcissedia (4 commits)")[![Crowly34](https://avatars.githubusercontent.com/u/29908764?v=4)](https://github.com/Crowly34 "Crowly34 (3 commits)")[![alexandersix](https://avatars.githubusercontent.com/u/11881203?v=4)](https://github.com/alexandersix "alexandersix (1 commits)")

---

Tags

hacktoberfestlaraveleventsactions

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/kirschbaum-development-laravel-actions/health.svg)

```
[![Health](https://phpackages.com/badges/kirschbaum-development-laravel-actions/health.svg)](https://phpackages.com/packages/kirschbaum-development-laravel-actions)
```

###  Alternatives

[tormjens/eventy

The WordPress filter/action system in Laravel

438912.9k16](/packages/tormjens-eventy)[chelout/laravel-relationship-events

Missing relationship events for Laravel

5252.3M17](/packages/chelout-laravel-relationship-events)

PHPackages © 2026

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