Convert Figma logo to code with AI

lorisleiva logolaravel-actions

⚡️ Laravel components that take care of one specific task

2,465
121
2,465
28

Top Related Projects

Fearless refactoring, it does a lot of smart checks to find certain errors.

⚗️ Adds code analysis to Laravel improving developer productivity and code quality.

IDE Helper for Laravel

Quick Overview

Laravel Actions is a package that allows you to create single-class, self-contained actions in Laravel applications. It combines command, job, and controller functionality into one cohesive unit, promoting code reusability and organization.

Pros

  • Simplifies code structure by combining multiple Laravel concepts into a single class
  • Promotes code reusability across different contexts (CLI, API, web)
  • Enhances testability by isolating business logic
  • Provides a clear and consistent way to organize application logic

Cons

  • Requires learning a new concept and structure, which may have a learning curve for some developers
  • May lead to over-engineering in simple applications where traditional Laravel patterns suffice
  • Could potentially conflict with existing Laravel conventions in some scenarios

Code Examples

  1. Creating a basic action:
use Lorisleiva\Actions\Concerns\AsAction;

class CreateUser
{
    use AsAction;

    public function handle(array $userData)
    {
        return User::create($userData);
    }
}
  1. Using an action as a controller:
class CreateUser
{
    use AsAction;

    public function asController(Request $request)
    {
        $user = $this->handle($request->validated());
        return redirect()->route('users.show', $user);
    }

    public function handle(array $userData)
    {
        return User::create($userData);
    }
}
  1. Running an action as a job:
CreateUser::dispatch($userData);

Getting Started

  1. Install the package via Composer:

    composer require lorisleiva/laravel-actions
    
  2. Create an action class:

    php artisan make:action CreateUser
    
  3. Implement the action logic in the handle method:

    class CreateUser
    {
        use AsAction;
    
        public function handle(array $userData)
        {
            return User::create($userData);
        }
    }
    
  4. Use the action in your application:

    $user = CreateUser::run($userData);
    

Competitor Comparisons

Fearless refactoring, it does a lot of smart checks to find certain errors.

Pros of Laravel Microscope

  • Focuses on static analysis and code quality improvement
  • Provides automated detection of potential bugs and inefficiencies
  • Offers a wider range of code checks and optimizations

Cons of Laravel Microscope

  • Requires more setup and configuration
  • May produce false positives in some cases
  • Doesn't provide a structure for organizing business logic

Code Comparison

Laravel Microscope (static analysis):

php artisan check:all

Laravel Actions (business logic organization):

class CreateUser extends Action
{
    public function handle($name, $email, $password)
    {
        return User::create(compact('name', 'email', 'password'));
    }
}

Laravel Microscope focuses on code analysis and improvement, while Laravel Actions provides a structure for organizing business logic. Microscope offers broader code quality checks, but Actions simplifies the implementation of complex operations. The choice between them depends on whether you prioritize code analysis or action organization in your Laravel project.

⚗️ Adds code analysis to Laravel improving developer productivity and code quality.

Pros of Larastan

  • Provides static analysis for Laravel applications, enhancing code quality and catching potential errors
  • Integrates seamlessly with PHPStan, offering powerful type inference and error detection
  • Supports custom PHPStan rules and extensions for Laravel-specific functionality

Cons of Larastan

  • Focuses solely on static analysis, not providing additional functionality like action classes
  • May require more setup and configuration compared to Laravel Actions
  • Can potentially produce false positives or require additional type annotations

Code Comparison

Larastan (PHPStan configuration):

includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:
    level: 5
    paths:
        - app
    checkMissingIterableValueType: false

Laravel Actions (Action class):

class CreateUser extends Action
{
    public function handle(string $name, string $email, string $password): User
    {
        return User::create(compact('name', 'email', 'password'));
    }
}

While Larastan focuses on static analysis and type checking, Laravel Actions provides a structure for organizing business logic into reusable classes. Larastan enhances code quality through analysis, while Laravel Actions offers a way to encapsulate and reuse application logic across different contexts.

IDE Helper for Laravel

Pros of Laravel IDE Helper

  • Enhances IDE autocomplete functionality for Laravel projects
  • Generates accurate PHPDoc annotations for Laravel facades and models
  • Supports multiple IDEs, including PhpStorm, VSCode, and Sublime Text

Cons of Laravel IDE Helper

  • Primarily focused on development environment and doesn't affect production code
  • Requires manual regeneration of helper files when project structure changes
  • May add some complexity to the development workflow for smaller projects

Code Comparison

Laravel IDE Helper:

php artisan ide-helper:generate
php artisan ide-helper:models
php artisan ide-helper:meta

Laravel Actions:

class CreateUser extends Action
{
    public function handle(string $name, string $email): User
    {
        return User::create(compact('name', 'email'));
    }
}

While Laravel IDE Helper focuses on improving the development experience through better IDE integration, Laravel Actions provides a way to encapsulate business logic into reusable classes. Laravel IDE Helper is more about enhancing tooling, whereas Laravel Actions offers a structural approach to organizing application logic.

Laravel IDE Helper is particularly useful for large projects with complex relationships and facades, while Laravel Actions shines in promoting code reusability and maintaining a clean architecture across different parts of an application.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

⚡️ Laravel Actions

Latest Version on Packagist GitHub Tests Action Status Total Downloads

hero

⚡ Classes that take care of one specific task.

This package introduces a new way of organising the logic of your Laravel applications by focusing on the actions your applications provide.

Instead of creating controllers, jobs, listeners and so on, it allows you to create a PHP class that handles a specific task and run that class as anything you want.

Therefore it encourages you to switch your focus from:

"What controllers do I need?", "should I make a FormRequest for this?", "should this run asynchronously in a job instead?", etc.

to:

"What does my application actually do?"

Installation

composer require lorisleiva/laravel-actions

Documentation

:books: Read the full documentation at laravelactions.com

Basic usage

Create your first action using php artisan make:action PublishANewArticle and define the asX methods when you want your action to be running as X. E.g. asController, asJob, asListener and/or asCommand.

class PublishANewArticle
{
    use AsAction;

    public function handle(User $author, string $title, string $body): Article
    {
        return $author->articles()->create([
            'title' => $title,
            'body' => $body,
        ]);
    }

    public function asController(Request $request): ArticleResource
    {
        $article = $this->handle(
            $request->user(),
            $request->get('title'),
            $request->get('body'),
        );

        return new ArticleResource($article);
    }

    public function asListener(NewProductReleased $event): void
    {
        $this->handle(
            $event->product->manager,
            $event->product->name . ' Released!',
            $event->product->description,
        );
    }
}

As an object

Now, you can run your action as an object by using the run method like so:

PublishANewArticle::run($author, 'My title', 'My content');

As a controller

Simply register your action as an invokable controller in a routes file.

Route::post('articles', PublishANewArticle::class)->middleware('auth');

As a listener

Simply register your action as a listener of the NewProductReleased event.

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

Then, the asListener method of your action will be called whenever the NewProductReleased event is dispatched.

event(new NewProductReleased($manager, 'Product title', 'Product description'));

And more...

On top of running your actions as objects, controllers and listeners, Laravel Actions also supports jobs, commands and even mocking your actions in tests.

📚 Check out the full documentation to learn everything that Laravel Actions has to offer.