iak/action

Simple actions for Laravel

Fund package maintenance!
Isak Berglind

1.1.0 2025-09-04 05:21 UTC

This package is auto-updated.

Last update: 2025-09-04 10:26:33 UTC


README

A simple way to organize your business logic in Laravel applications.

While you can install this, I would encourage you to simply copy the action file and take ownership of it. The logic is not complicated, and it will allow you to add/remove/update the features you like.

Installation

composer require iak/action

Basic Usage

Creating an Action

<?php

namespace App\Actions;

use Iak\Action\Action;

class SayHelloAction extends Action
{
    public function handle()
    {
        return "Hello";
    }
}

Using an Action

<?php

namespace App\Http\Controllers;

use App\Actions\SayHelloAction;

class HomeController extends Controller
{
    public function index(SayHelloAction $action)
    {
        $result = $action->handle();

        return response()->json($result);
    }
}

Static Methods

Actions provide helpful static methods:

// Create an instance
$action = SayHelloAction::make();

// Create a fake for testing
$action = SayHelloAction::fake();

Events

Actions can emit and listen to events:

<?php

namespace App\Actions;

use Iak\Action\Action;
use Iak\Action\EmitsEvents;

#[EmitsEvents(['hello_said'])]
class SayHelloAction extends Action
{
    public function handle()
    {
        $result = "Hello";
        
        $this->event('hello_said', $result);

        return $result;
    }
}

Listen to events:

$action = SayHelloAction::make()
    ->on('hello_said', function ($result) {
        // Do something when hello is said
        Log::info("Hello said: {$result}");
    })
    ->handle();

Testing

<?php

use App\Actions\SayHelloAction;

it('says hello', function () {
    $result = SayHelloAction::make()->handle();
    
    expect($result)->toBe('Hello');
});

it('can fake an action', function () {
    $action = SayHelloAction::fake();
    
    expect($action)->toBeInstanceOf(MockInterface::class);
});

Requirements

  • PHP 8.2+
  • Laravel 11.0+ or 12.0+

License

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

Contributing

Please see CONTRIBUTING for details.

Credits

Support

If you discover any issues or have questions, please open an issue.