phplaravelvalidationlaravel-5

Laravel how to pass value to Rulee::exist()


I have the following code:

$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)]);
                })],
            ]);

but it gives me the following error:

"Undefined variable: postalcode"

so what I want is to pass variable $postalcode to the rule but I do not know how?


Solution

  • Rule::exists('zipcodes')->where(function ($query) use($postalcode){
                        $query->whereRaw('REPLACE(POSTAL_CODE,\' \',\'\')= ?',[str_replace(' ','',$postalcode)]);
                    });
    

    You forgot to write use($postalcode);