十年網站開發(fā)經驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網站問題一站解決
下面由Laravel教程欄目給大家分享一個Laravel中的管道的使用實例,希望對需要的朋友有所幫助!

從代碼的角度介紹管道的實際使用方式。有關管道的說明,網上已有較多的篇幅介紹,自行查閱。
本篇博客是使用管道處理名字, 實現(xiàn)統(tǒng)一處理的目的。
背景:
目前能找到的使用管道的介紹也很多,大多停留在對其介紹和引導,真正的深入到代碼的部分不多。根據介紹,使用管道也有一定的阻礙,這里分享一篇關于使用管道的詳細的代碼實例,僅供參考。
本篇介紹是自己真實使用的過程的代碼摘錄,親自測試,真實可用。只為拋磚引玉,不喜勿噴。
路由器部分
Route::get('/pipe', ['as'=>'pipe', 'uses'=>'PipeController@index']);控制代碼
input('name');
// $name = Str::random(10);
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'),
]);
});
}
}二、管道部分目錄結構如下:
├─app │ │ User.php │ ├─Http │ │ ...│ │ │ ├─Models │ │ ...│ │ │ ├─Pipes │ │ │ BothSidesWords.php │ │ │ LeftWords.php │ │ │ RightWords.php │ │ │ │ │ └─Contracts │ │ PipeContracts.php
interface的代碼
路徑app/Pipes/Contracts/Pipe.php下的代碼如下:
三個管道的類的代碼
LeftWords.php的代碼
LeftWords.php的代碼
BothSidesWords.php的代碼這里我們使用管道默認的方法
handle,你可以自定義方法名。像下面這樣定義myHandleMethod為處理方法名稱。return app(Pipeline::class) ->send($name) ->through($this->pipes) ->via('myHandleMethod') ->then(function ($content) { return User::create([ 'name' => $content, 'email'=>Str::random(10).'@gmail.com', 'password'=>Hash::make('password'), ]); });你這樣定義后,修改你的
三、結果說明interface,同時修改你的實現(xiàn)類即可。訪問
http://localhost/pipe?name=lisa之后,能成功打印出獲取的結果。User表內部,有數(shù)據保存成功。{ "name": "[left-lisa-right]", "email": "3riSrDuBFv@gmail.com", "updated_at": "2020-09-05T05:57:14.000000Z", "created_at": "2020-09-05T05:57:14.000000Z", "id": 15 }
網頁題目:Laravel中使用管道處理名字,實現(xiàn)統(tǒng)一處理
網頁地址:http://m.jiaotiyi.com/article/cjcddo.html