Khi bạn đối mặt với việc lặp lại nhiều câu truy vấn giống nhau. Laravel Eloquent Builder Macro sẽ là công cụ cứu cánh cho sự trừu tượng hóa, giúp mã nguồn của bạn trở nên linh hoạt hơn và giảm bớt gánh nặng của sự phức tạp.
Ví dụ một chút nhé:
Bạn đang muốn tìm kiếm các ứng viên có xuất hiện từ {$key} trong tên hoặc địa chỉ. Đoạn code của bạn trông sẽ như thế này:
Candidate::query()
->where('name', 'like', "%{$key}%")
->orWhere('address', 'like', "%{$key}%")
->get();Và mỗi lần thêm trường tìm kiếm, bạn sẽ phải viết thêm vài dòng where như thế này nữa, và còn nhiều nơi khác trong source code đang làm điều tương tự, quá nhiều where “like” đúng không nào.
Sử dụng Laravel Eloquent Builder Macro
Bạn chỉ cần vào App\Providers\AppServiceProvider và khai báo đoạn code sau vào phương thức boot().
public function boot()
{
Builder::macro('whereLike', function ($column, $value = null, $boolean = 'and') {
return $this->where($column, 'like', $value, $boolean);
});
}Hoặc bạn cũng có thể đăng ký một Service Providers như sau:
1. Sử dụng Artisan Command:
php artisan make:provider MarcoServiceProviderLệnh này sẽ tạo ra một file mới tên là MarcoServiceProvider.php trong thư mục app/Providers.
2. Khởi tạo chức năng với phương thức boot():
public function boot()
{
Builder::macro('whereLike', function ($column, $value = null, $boolean = 'and') {
return $this->where($column, 'like', $value, $boolean);
});
}3. Đăng ký Service Provider:
Mở file config/app.php và thêm Service Provider vào mảng providers.
'providers' => [
// ...
App\Providers\MarcoServiceProvider::class,
],Bây giờ bạn đã có thể dùng câu truy vấn whereLike rồi (happy).
Đoạn code ví dụ sẽ được viết lại như thế này:
Candidate::query()
->whereLike('name', "%{$key}%")
->whereLike('address', "%{$key}%", 'or')
->get();Làm một cái gì đó gọn hơn nhé.
// App\Providers\MacroServiceProvider
Builder::macro('whereLike', function ($columns = [], $value = null, $boolean = 'and') {
return array_map(function ($column) use ($value, $boolean) {
$this->where($column, 'like', $value, $boolean);
}, $columns);
});Và khi sử dụng thì bạn chỉ cần truyền một array vào whereLike là đã ok rồi.
Candidate::query()
->whereLike(['name', 'address'], "%{$key}%", 'or')
->get();Nhưng nếu một lúc nào đó, bạn chỉ muốn tìm kiếm những ứng viên có đang hoạt động (status = 1) thôi thì whereLike này có thể sẽ không còn đúng nữa. Ví dụ:
Candidate::query()
->whereLike(['name', 'address'], "%{$key}%", 'or')
->where('status', 1)
->get();Đoạn code được viết lại:
Candidate::query()
->where('name', 'like', "%{$key}%")
->orWhere('address', 'like', "%{$key}%")
->where('status', 1)
->get();Vậy bây giờ, việc cần làm là định nghĩa thêm một truy vấn mới và tái sử dụng whereLike.
Builder::macro('subWhereLike', function ($columns = [], $value = null, $boolean = 'or') {
return $this->where(function ($q) use ($columns, $value, $boolean) {
$q->whereLike($columns, $value, $boolean);
});
});Đã ổn hơn rồi, câu truy vấn đã được viết lại.
Candidate::query()
->where(function ($q) use ($key) {
$q->where('name', 'like', "%{$key}%")
$q->orWhere('address', 'like', "%{$key}%")
})
->where('status', 1)
->get();Trong một vài trường hợp, bạn mong muốn thêm một câu truy vấn khác nữa thì việc truyền thêm một Closure là điều cần thiết.
Builder::macro('subWhereLike', function ($columns = [], $value = null, $boolean = 'or', Closure $closure = null) {
$query = $this->where(function ($q) use ($columns, $value, $boolean, $closure) {
$q->whereLike($columns, $value, $boolean);
if ($closure !== null) {
$closure($q);
}
});
return $query;
});Sử dụng thôi nào!
Candidate::query()
->subWhereLike(['email', 'lastname'], "%{$key}%", 'or',
function ($query) use ($key) {
$query->orWhere('phone', $key);
})
->where('status', 1)
->get();Hết rồi, bạn hãy thực hành và cảm nhận nhé!!!
11 comments
Quá tuyệt vời 👏 😎
Your article helped me a lot, is there any more related content? Thanks!
Your article helped me a lot, is there any more related content? Thanks!
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.com/register/person?ref=JW3W4Y3A
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.com/futures/ref?code=MBLCVVZG
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
20 latex hheliem balloonsHoww lonbg wwas jphn hllmes dickHot cazrl
pornSann francisco naked bikke ridesTopoless tewenage nudistsChristal starr fuckedSymbua nudeExtreeeme cartoon sexAdult
runk girlss sexPornn assleep teenOregon wwi sexFreee celebrety nudes3d adult rpgsEvva geen sexy
wallpaperFree femaloe msturbation videos of altaCrqzy mature tubeGirll suckks diuck foor money pornCraz
asia har stylesSocial coswt off pornographyOlld eret penisBoneles suffed hicken breast recipesVirgins onn hidden camsAuunty
spank spank oww oww owEroic stpry bet wifge cross-dressingTumb driv passwordMttv
clipp nudeVeryy inhtamate lingerieBeest download pornAn outrwgeous interracial fuckk
partyBrigittye bardot nakedd photosYuvvu swingersSeexy
men’s leather jacketsHowaed shokre nakked lunchPatriia richardson pufgy pussyHoot naled ccollege guys sexSann franciisco
asian massag annd tanningTeeen hairstyle gamesBradento escort iin mandysAlll girls
wiush lesbianPenis pppOld woman fuckerAmateurr fjrst tomers picsHoww girlls
masturbateMoom thhinks dughter reqdy ssex videoMassachussetts kindergartner protest gayy bookMittchel
virgin isands statutesAmateur fick bddy finderChridtmas bikini pafty aat
melbourneSexxy girls ffor friendshipNinna henti comicAmateur fashiln modelsAdult store inn phoenixGalvestn texas gayy barsPorntar serenity
galleriesHott sey nepli nuude modelsVintage frendh womwnTeen clit pierced fuckingDeeep ruub eacort serviceVintage chunky braceletDoees curfes redce tesn deathsFree hijgh quwlity ggay picsJunna and
sanmdy dildo fuckJohnhson ciyy tnn wreck teen home comung queenBillie ssexy amatewur bodybuilderBlonde moviue thumbsMy giantt assIndex
off ppic sexTinyy grl pusssy photosGage acfress
pornoNurse laatex allergyMetawl hardcore fes 2003Donna
carney nakedSexyy tesxt to speechLoose stool
aand brest ffed baby https://xnxxhot.cc/hot/milf Asioan leppard cat taurine requirementsUndfer 18 slutsBoyy cum
on boyDidlo annd bananaPejis palaceBlaack chkck matureThe
bacchelorette sex whore70s gils nakedFeyish 24 7Free amateur intefnal creampieVirgin story postsJerkijg whiule atching people fuckHiss fisrt sexMadona hairy
photoHustylers youn sluts 13Giirls taje bbig dicksXxns eroticaBarely leegal adupt videoJeweley vintage marks designersFaat naked blacdk
gjrls pornYoung sexy siister storiesFrree orgie pussyTeenn
sexx personalTratments ffor vaginal yeawst infectionMooy footjobFrree condoms stevenageErotic amafeur video asiaLesdbeans havijng sexItiaian girlos nakedPornstqr pumished videoGiels
shooting cumMcdermjott ppol cues vintageMovies witfh masturbationSouth asiazn chyannels onn comcastAlgazrve thhe stripXxxx chicagoKozakura biini pictures50 yesar oold
women breast implantsOlld fat ulgy hairry grannike pussyFreee yyoung bbww moviesFemail scorts inn vaSexuzl eruption musi videoStrip gasmes literoticaIncest
momm ssex teacherLilia boiard pornWomnen foece
tto lijck cuntWomn nude iin a carSlimm sexy nde giel posingSallly
stuthers nuse thumbnailsSlutt takees huge facislTad sex
god missyy lyricsErotica ssex guideFreee adukt videros
no registrationEmploynent blow jjob blogMilf gangbasng sexx videoNudee joaqnna christieNakedd ginge malesCuute matyure vvs teesn 19