Laravel Actions Package

Laravel Actions Package

Laravel Actions is a package by Loris Leiva which introduces a new way of organizing the logic of your Laravel applications by focusing on the actions your applications provide.

Similarly to how VueJS components regroup HTML, JavaScript, and CSS together, Laravel Actions regroup the authorization, validation, and execution of a task in one class that can be used as an invokable controller, as a plain object, as a dispatchable job and as an event listener.

Here’s a basic example of the package’s idea of an action class from the readme:

class PublishANewArticle extends Action
{
    public function authorize()
    {
        return $this->user()->hasRole('author');
    }

    public function rules()
    {
        return [
            'title' => 'required',
            'body' => 'required|min:10',
        ];
    }

    public function handle()
    {
        return Article::create($this->validated());
    }
}

And then you can use these actions in various ways, such as a plain object, a dispatchable job, or an event listener:

// Plain Object
$action = new PublishANewArticle([
    'title' => 'My blog post',
    'body' => 'Lorem ipsum.',
]);

$article = $action->run();

// Dispatchable Job
PublishANewArticle::dispatch([
    'title' => 'My blog post',
    'body' => 'Lorem ipsum.',
]);

// An event listener
class ProductCreated
{
    public $title;
    public $body;

    public function __construct($title, $body)
    {
        $this->title = $title;
        $this->body = $body;
    }
}

Event::listen(ProductCreated::class, PublishANewArticle::class);

event(new ProductCreated('My new SaaS application', 'Lorem Ipsum.'));

To learn more about the full capabilities of this package, including source code, documentation, and examples, check out the project on GitHub at lorisleiva/laravel-actions.

Filed in: News
Laravel News Partners

Laravel Jobs

Senior Full-Stack Developer
Atlanta, GA - (remote) USA ONLY
Curricula
PHP Laravel Developer
London
Investoo
Senior Backend Developer
Australia
Tixel
CTO
Copenhagen
Tjommi
Looking for Senior Full-stack Laravel/React.js Javascript API Developer - Immediate (Full-time)
Remote
ApproveMe // Document Signing

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.