Laravel validation custom rule

1.7k Views Asked by At

How to do that this function would look for a row in table not by given name John but by inputed 'name' ?

public function validation($request)
{
    return $this->validate($request, [
        'name' => 'required|max:255',
        'last_name' => 'required|max:255',
        'code' =>  ['required',Rule::exists('users')->where(function ($query) {
            $query->where('name', '=', 'John');

        }), ],
    ]);
} 
2

There are 2 best solutions below

0
On

Check your param and change 'John' to request->name

public function validation(Request $request){
  return $this->validate($request, [
          'name'      => 'required|max:255',
          'last_name' => 'required|max:255',
          'code'      => [
                          'required',
                          Rule::exists('users')
                              ->where('name', $request->name)
                        ],
        ]);
}

0
On

You have to use use keyword for this and pass the $request object inside this like

public function validation($request)
{
    return $this->validate($request, [
        'name' => 'required|max:255',
        'last_name' => 'required|max:255',
        'code' =>  ['required',Rule::exists('users')->where(function ($query) use ($request) {
            $query->where('name', '=', $request->name);

        }), ],
    ]);
} 

or, you can use like this without passing a callback function in where as

public function validation($request)
{
    return $this->validate($request, [
        'name' => 'required|max:255',
        'last_name' => 'required|max:255',
        'code' =>  array('required',Rule::exists('users')->where('name', '=', $request->name);),
    ]);
}