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
X3 Builders
Lead Front End Developer
Remote
continued
Full-Stack Laravel Developer
Cologne
Revive Interior
Intermediate PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Remote
continued
Senior PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Remote
continued
Laravel Developer
Amsterdam (partially remote possible)
Let's Book
Web Developer (Laravel)
Tweed Heads, New South Wales, AUSTRALIA
Tursa Employment & Training