PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

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

 November 15, 2022     laravel, laravel-6, php, validation     No comments   

Issue

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?


Solution

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



Answered By - sumnx
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing