'How to attach id of table to request in laravel while validating?
The Laravel form request validator runs a query when using exists.
'item_name'=>'required|exists:items,name'
After validating for saving data I need to again run the same query and find items.id Can I prevent this extra query? I'm using validation for 1000 rows in csv. Please suggest other optimization techniques if any.
Solution 1:[1]
I finally used collection of all items inside FormRequest constructor. Item::all(); this would get huge amount of data but would prevent running query n times.
Inside witValidator function
public function withValidator(Validator $validator,Array $row): Validator
{
$validator->after(function ($validator)use($row) {
$exists = $this->item_collection->firstWhere('id',$this->id);
if(!$exists){
$validator->errors()->add('id','id not found');
}
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yogesh.galav |
