Is there a way of referencing another field when specifying the exists validation rule in Laravel?
My request :
public function rules()
{
return [
'numero_de_somme' => 'unique:personnels,numero_de_somme|exists:fonctionnaire,num_somme',
'cin' => 'unique:personnels,cin|exists:fonctionnaire,cin',
];
}
in my validation rules I want to be able to make sure that:
num_somme
exists within thefonctionnaire
tablecin
exists within the fonctionnaire table andcin
input must be on the same row of thenum_somme
num_somme : 12345 cin : s89745
num_somme : 78945 cin : U10125
Explaining : for example
- 1st scenario if the input
num_somme
= 12345 andcin
= U10125 the validation must fail - 2nd scenario if the input
num_somme
= 12345 andcin
= s89745 the validation must success
I hope this makes sense.
Thank you
You can simply use this:
The SQL query is like below:
I came across the same need today and I think I have a solution using the validation Rule class: Rule example.
Here is my scenario: I have an email verifications table and I want to ensure that a passed machine code and activation code exist on the same row.
Be sure to include
use Illuminate\Validation\Rule;
The first argument in the exists method is the table and the second is the custom column name I'm using for the 'mc' field. I pass the second column I want to check using the 'use' keyword and then use that field in a a where clause.
You can achieve validating multipe columns by using Rule.
Include :
use Illuminate\Validation\Rule;
use Validator;
Here in my example I'm checking u_id and Id which is in same row and 2 columns.
Explaining : for example
My DB HAS 2 ROWS IN tax TABLE
id = 1 , u_id = 1, tax = "GST" , value -> 8
id = 2 , u_id = 2, tax = "GST" , value -> 5
1st scenario if the input id = 2 and u_id = 1 the validation must fail because this row belongs to u_id = 2.
2nd scenario if the input id = 2 and u_id = 2 the validation must success
i managed to solve it using the most simple method
numero_de_somme
'numero_de_somme' => 'unique:personnels,numero_de_somme|exists:fonctionnaire,num_somme,cin,'.Request::get('cin'),
cin
'cin' => 'unique:personnels,cin|exists:fonctionnaire,cin',
PS . don't forget to call
use Illuminate\Http\Request;