Laravel 如何将值传递给 Rulee::exist()

问题描述 投票:0回答:2

我有以下代码:

$postalcode=$data['postal_code'];   
 return Validator::make($data, [
                'name' => ['required','string','max:255'],
                'email' => ['required','string','email','max:255','unique:users'],
                'password' => ['required','string','min:8','confirmed'],
                'postal_code' =>['required','string','max:255',Rule::exists('zipcodes')->where(function ($query) {
                    $query->whereRaw('REPLACE(POSTAL_CODE,\' \',\'\')= ?',[str_replace(' ','',$postalcode)]);
                })],
            ]);

但它给了我以下错误:

“未定义的变量:邮政编码”

所以我想要的是将变量 $postalcode 传递给规则,但我不知道如何?

php laravel validation laravel-5
2个回答
0
投票
Rule::exists('zipcodes')->where(function ($query) use($postalcode){
                    $query->whereRaw('REPLACE(POSTAL_CODE,\' \',\'\')= ?',[str_replace(' ','',$postalcode)]);
                });

你忘了写

use($postalcode)


0
投票
Try with this, pass paramiter using laravel eager loading (function ($query) use ($postalcode)).Now Don't give Undefined variable: postalcode.

$postalcode=$data['postal_code'];   
 return Validator::make($data, [
                    'name' => ['required','string','max:255'],
                    'email' => ['required','string','email','max:255','unique:users'],
                    'password' => ['required','string','min:8','confirmed'],
                    'postal_code' =>['required','string','max:255',Rule::exists('zipcodes')->where(function ($query) use ($postalcode){
                        $query->whereRaw('REPLACE(POSTAL_CODE)= ?',[str_replace(' ','',$postalcode)]);
                    })],
                ]);
© www.soinside.com 2019 - 2024. All rights reserved.