Using Laravel Pipeline with Custom Pipes for Request Processing
This article explains how to set up a Laravel route and controller that leverages the Pipeline class to pass a request through three custom pipe classes—LeftWords, RightWords, and BothSidesWords—modifying the input and storing the result as a new user record.
In this article we demonstrate how to use Laravel's Pipeline feature to process a request through a series of custom pipe classes.
Controller and route
Route::get('/pipe', ['as' => 'pipe', 'uses' => 'PipeController@index']); <?php
namespace App\Http\Controllers;
use App\Pipes\LeftWords;
use App\Pipes\RightWords;
use App\Pipes\BothSidesWords;
use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;
use App\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
class PipeController extends Controller
{
protected $pipes = [
LeftWords::class,
RightWords::class,
BothSidesWords::class,
];
public function index(Request $request)
{
$name = $request->input('name');
return app(Pipeline::class)
->send($name)
->through($this->pipes)
->then(function ($content) {
return User::create([
'name' => $content,
'email' => Str::random(10) . '@gmail.com',
'password' => Hash::make('password'),
]);
});
}
}Pipe contract
<?php
namespace App\Pipes\Contracts;
use Closure;
interface PipeContracts
{
public function handle($body, Closure $next);
}Pipe implementations
<?php
namespace App\Pipes;
use App\Pipes\Contracts\PipeContracts;
use Closure;
class LeftWords implements PipeContracts
{
public function handle($body, Closure $next)
{
$body = 'left-' . $body;
return $next($body);
}
} <?php
namespace App\Pipes;
use App\Pipes\Contracts\PipeContracts;
use Closure;
class RightWords implements PipeContracts
{
public function handle($body, Closure $next)
{
$body = $body . '-right';
return $next($body);
}
} <?php
namespace App\Pipes;
use App\Pipes\Contracts\PipeContracts;
use Closure;
class BothSidesWords implements PipeContracts
{
public function handle($body, Closure $next)
{
$body = '[' . $body . ']';
return $next($body);
}
}The directory layout places the pipe classes under app/Pipes and the contract under app/Pipes/Contracts. By calling http://localhost/pipe?name=lisa the pipeline produces a user record with the name [left-lisa-right] and stores it in the users table.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
