Skip to content
Advertisement

How do I do Laravel form validation when value of one field decides validity of the other field

I have a form. Type field is a drop-down and has only two possible values. Second field is bcode.
E.g. if table has data like-

ID  TYPE  BCODE
1     1     2
2     1     3
3     2     2
4     1     4
5     2     2

Now I am making a popup form to insert record in this table. So if type is entered 1 and bcode is entered 2,3 or 4 its already in table so it will be invalid but any other numeric value will be valid. Similarly if type is entered 2 then bcode can’t be anything other than 2,3 or 4. All other values will be invalid.

I read the Laravel docs here-
https://laravel.com/docs/6.x/validation#custom-validation-rules
But did not find anything.
Anyone tried something similar?

Advertisement

Answer

Assuming your table structure is like in your example and its called type_bcode, I’m offering the following solution:

  1. Create custom rule by running php artisan make:rule TypeBcode
    It should look like this:

    private $type;
    
    public function __construct($type)
    {
        $this->type = $type;
    }
    public function passes($attribute, $value)
    {
        $type_bcode = DB::table('type_bcode')
            ->where('type', $this->type)
            ->get()
            ->pluck('bcode')
            ->toArray();
    
        return in_array($value, $type_bcode);
    }
    public function message()
    {
        return 'The validation error message.';
    }
    
  2. In your controllers store function do this:

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required',
            'bcode' => ['required', new TypeBcode($request->type)],
        ]);
        if ($validator->fails()) {
            //some action
        }
        //some action
    }
    

Hope this will help

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement