Search code examples
mysqlformslaravellaravel-5.3laravel-validation

Checking 2 unique codes against the table and then registering the form


I've 2 different tables with 2 columns [code,status] each and the column 'code' contains unique code in integers (392,21,2981,2743,..etc) and they are about 100 in each table while the status tells if these codes were used or not.

I want the form to be only submitted when both of the provided codes from the user match the codes in those 2 tables and have the status '0'

I could create a very simple validation in the controller but that dosen't make much sense to what i just explained

public function formValidationPost(Request $request)
    {

        $this->validate($request,[
                'name' => 'required|min:5|max:35',
                'email' => 'required|email|unique:users',
                'mobile' => 'required|numeric',
                'code_a' => 'bail|required|exists:code_a,code',
                'code_b' => 'bail|required|exists:code_b,code'
            ],[
                'name.required' => ' The name field is required.',
                'name.min' => ' The name must be at least 5 characters.',
                'name.max' => ' The name may not be greater than 35 characters.',
            ]);

        dd('You  successfully added all fields.');
    }

So with my validation rules I want to be able to make sure that:

  • Form doesn't submit unless both the provided codes are matched in the database ( code_a[table] and code_b[table] ) and their status to be '0'

I hope this makes sense.

Thanks


Solution

  • Reference

    use Illuminate\Validation\Rule;
    
    $this->validate($request,
    [...
        'mobile' => 'required|numeric',
        'code_a' => [
            'bail',
            'required',
            Rule::exists('code_a', 'code')->where(function($query) {
                $query->where('status', 0);
            })
        ],
        'code_b' => [
            'bail',
            'required',
            Rule::exists('code_b', 'code')->where(function($query) {
                $query->where('status', 0);
            })
        ]
    ],
    [...]);