Skip to content
Andrew Dabych
Go back

Laravel Pipeline: A Powerful Tool for Managing Data Flows

Laravel pipelines illustration

What is Laravel Pipeline and how does it work?

Pipeline is an implementation of the Pipeline Pattern, which allows an object to pass through a series of handlers, each performing a specific task. This is a great way to structure code following the Single Responsibility Principle (SRP), which is part of SOLID.

Key features of Pipeline

Pipeline is especially useful in scenarios like:

  1. Object transformation - when you need to apply multiple handlers to modify or enrich an object.
  2. Model processing before saving or after updating - when you need to execute several independent processes, such as creating relationships, sending notifications, or integrating with third-party services.

Example of Laravel Pipeline usage

Let’s say that after creating a user, we need to:

Instead of handling this logic in one place, Pipeline can be used:

use Illuminate\Pipeline\Pipeline;

$user = Pipeline::send($user)
            ->through([
                GenerateProfilePhoto::class,
                ActivateSubscription::class,
                SendWelcomeEmail::class,
            ])
            ->then(fn (User $user) => $user);

Each handler is a separate class, like this:

class GenerateProfilePhoto {
    public function handle(User $user, Closure $next) {
        // Generate profile photo
        $user->profile_photo = 'default.png';

        return $next($user);
    }
}

The key takeaway: each class receives the $user object, performs its logic, and passes it to the next handler using $next($user). This is similar to middleware but can be used beyond HTTP requests, in any business logic.

Why use Pipeline?

  1. Cleaner and more readable code - each process is in its own class.
  2. Flexibility - easily add or remove handlers.
  3. Reusability - the same classes can be used in different parts of the application.

Additional resources

Conclusion

If you need to process data sequentially, Pipeline is a great way to do it efficiently and elegantly. Now that this tool is officially documented in Laravel 10, using it is easier than ever.


Share this post on:

Previous Post
Keep Learning, Stay Successful in Tech Industry