DEV Community

Cover image for Action pattern in Laravel 🧩
Nikola Perišić
Nikola Perišić

Posted on

Action pattern in Laravel 🧩

In the dynamic world of Laravel development, staying up-to-date with the latest patterns and practices is crucial.

Today, let's delve into the Action Pattern.

The whole code you can find here.


The Action Pattern is a powerful paradigm that promotes modular, reusable, and testable code. At its core, it advocates breaking down complex operations into smaller, focused actions, each responsible for a specific task. This not only improves code organization but also facilitates easier maintenance and debugging 🧩

Action pattern in Laravel|Laravel action pattern


Code example

Let's take a look at a code snippet that illustrates the Action Pattern in practice:

UserController.php

public function destroy(DeleteTeamRequest $request, Team $team, DeleteTeamAction $action): Response
{
    $action->handle($request->user(), $team);

    return redirect()->route('dashboard');
}
Enter fullscreen mode Exit fullscreen mode

DeleteTeamAction.php

<?php

namespace App\Actions;

use App\Models\Team;
use App\Models\User;

class DeleteTeamAction
{
    public function handle(User $user, Team $team)
    {
        // Ensure the user has permission to delete the team
        if ($user->can('delete', $team)) {
            $team->delete();

            return true;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key components

  1. Request validation: DeleteTeamRequest ensures the validity of incoming requests, maintaining the integrity and security of our application 🔒

  2. Dependency injection: Leveraging Laravel's powerful IoC container, we inject the Team model and DeleteTeamAction, promoting dependency and flexibility 🔄

  3. Action handling: The handle method of the DeleteTeamAction encapsulates the logic for deleting a team. By isolating this logic, we promote reusability and maintenance 🧰

  4. Redirection: After successfully deleting the team, the user is redirected to the dashboard 📲


Conclusion 🌟

Breaking down complex operations into smaller, modular actions not only improves code readability but also facilitates maintenance and testing. So, the next time you're faced with a challenging task in your Laravel project, don't forget the power of the Action Pattern.

Keep coding brilliantly!

Top comments (0)