Laravel Actions Package
Published on by Paul Redmond
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 JobPublishANewArticle::dispatch([ 'title' => 'My blog post', 'body' => 'Lorem ipsum.',]); // An event listenerclass 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.