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

Software Engineer Lead (PHP)
Remote
CivicPlus, LLC
Full-time Senior Web Developer
Detroit, MI
Wayne State University
Senior Software Engineer
Sydney, Australia
FoodByUs
Full Stack Engineer
Remote or Medford, Oregon
Empire Medical
Laravel Developer (fulltime - Dutch only)
Netherlands
Qbixx | Webservices
Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Senior Quality Assurance Engineer
Remote
Bisnow Media