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


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Laravel Developer
San Jose, CA - Must Be Local
X3 Builders
Experienced PHP Developer
Wilmington, NC
Queensboro Shirt Company
Senior Laravel developer
Netherlands, Rotterdam
Pionect
Senior Laravel Engineer
Remote okay (must already live in USA)
Hawthorne Effect
Senior Software Engineer (Remote - Contract)
Remote
Koodi Systems
PHP Developer
Pittsburgh / Remote
Sequoia Waste Solutions
Software Developer
Eindhoven
Simac IDS