search
HomePHP FrameworkLaravelUse pipes to process names in Laravel to achieve unified processing

The following is a tutorial column to share with you an example of using pipes in Laravel, I hope it will be helpful to friends in need!

Introduces the actual use of pipelines from a code perspective. There is a lot of information about pipelines on the Internet, so check it out by yourself.

This blog uses pipelines to process names to achieve unified processing. Use pipes to process names in Laravel to achieve unified processing

Background:

There are many introductions to the use of pipelines that can be found at present, most of which stay at the introduction and guidance, and there are not many parts that really go deep into the code. According to the introduction, there are certain obstacles to using pipelines. Here is a detailed code example on using pipelines for reference only.
This introduction is a code excerpt of the process that I actually used. I tested it myself and it is actually usable. Just to attract attention, don't criticize if you don't like it.



1. Controller

<?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(&#39;name&#39;);
        // $name = Str::random(10);

        return app(Pipeline::class)
            ->send($name)
            ->through($this->pipes)
            ->then(function ($content) {
                return User::create([
                    &#39;name&#39; => $content,
                    &#39;email&#39;=>Str::random(10).&#39;@gmail.com&#39;,
                    &#39;password&#39;=>Hash::make(&#39;password&#39;),
                ]);
            });
    }
}

2. Pipeline part

The directory structure is as follows:

├─app
│  │  User.php
│  ├─Http
│  │  ...│  │
│  ├─Models
│  │  ...│  │
│  ├─Pipes
│  │  │  BothSidesWords.php
│  │  │  LeftWords.php
│  │  │  RightWords.php
│  │  │
│  │  └─Contracts
│  │          PipeContracts.php

interface
    code
  • The code under the path

    app/Pipes/Contracts/Pipe.php is as follows:
    <pre class='brush:php;toolbar:false;'> &lt;?php namespace App\Pipes\Contracts; use Closure; interface PipeContracts { public function handle($body, Closure $next); }</pre>

  • The code of the three pipe classes
    LeftWords.php
  • The code


    <pre class="brush:php;toolbar:false">  &lt;?php namespace App\Pipes; use App\Pipes\Contracts\PipeContracts; use Closure; class LeftWords implements PipeContracts{ public function handle($body, Closure $next) { // TODO: Implement handle() method. $body = &amp;#39;left-&amp;#39;.$body; return $next($body); } }</pre> </pre>

    LeftWords.php
  • code
  <?php  namespace App\Pipes;

 use App\Pipes\Contracts\PipeContracts;
 use Closure;

 class RightWords implements PipeContracts{
     public function handle($body, Closure $next)
     {
         // TODO: Implement handle() method.

         $body = $body.&#39;-right&#39;;

         return $next($body);
     }
 }

BothSidesWords.phpcode

  <?php  namespace App\Pipes;

 use App\Pipes\Contracts\PipeContracts;
 use Closure;

 class BothSidesWords implements PipeContracts{
     public function handle($body, Closure $next)
     {
         // TODO: Implement handle() method.

         $body = &#39;[&#39;.$body.&#39;]&#39;;

         return $next($body);
     }
 }

Here we use the pipeline default methodhandle , you can customize the method name. Define

myHandleMethod

as the name of the processing method as follows. <pre class="brush:php;toolbar:false">return app(Pipeline::class)         -&gt;send($name)         -&gt;through($this-&gt;pipes)         -&gt;via('myHandleMethod')         -&gt;then(function ($content) {             return User::create([                 'name' =&gt; $content,                 'email'=&gt;Str::random(10).'@gmail.com',                 'password'=&gt;Hash::make('password'),             ]);         });</pre>After you define it like this, modify your interface and modify your implementation class at the same time.

3. Result Description

User

In the table, there is data saved successfully. <pre class='brush:php;toolbar:false;'>{ &quot;name&quot;: &quot;[left-lisa-right]&quot;, &quot;email&quot;: &quot;3riSrDuBFv@gmail.com&quot;, &quot;updated_at&quot;: &quot;2020-09-05T05:57:14.000000Z&quot;, &quot;created_at&quot;: &quot;2020-09-05T05:57:14.000000Z&quot;, &quot;id&quot;: 15 }</pre>

The above is the detailed content of Use pipes to process names in Laravel to achieve unified processing. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
What is the latest version of Laravel?What is the latest version of Laravel?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

How does the newest Laravel version simplify development?How does the newest Laravel version simplify development?Apr 24, 2025 pm 05:01 PM

ThelatestLaravelversionenhancesdevelopmentwith:1)Simplifiedroutingusingimplicitmodelbinding,2)EnhancedEloquentcapabilitieswithnewquerymethods,and3)ImprovedsupportformodernPHPfeatureslikenamedarguments,makingcodingmoreefficientandenjoyable.

Where can I find the release notes for the latest Laravel version?Where can I find the release notes for the latest Laravel version?Apr 24, 2025 pm 04:53 PM

You can find the release notes for the latest Laravel version at laravel.com/docs. 1) Release Notes provide detailed information on new features, bug fixes and improvements. 2) They contain examples and explanations to help understand the application of new features. 3) Pay attention to the potential complexity and backward compatibility issues of new features. 4) Regular review of release notes can keep it updated and inspire innovation.

The Remote Toolkit: Essential Tools for Staying Connected in Distributed TeamsThe Remote Toolkit: Essential Tools for Staying Connected in Distributed TeamsApr 24, 2025 pm 04:37 PM

Theessentialtoolsforstayingconnectedindistributedteamsinclude:1)CommunicationtoolslikeZoom,MicrosoftTeams,Slack,andDiscordforeffectivecommunication;2)ProjectmanagementtoolssuchasTrello,Asana,andJirafortaskmanagementandworkfloworganization;3)Collabora

Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.