0

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.

Yogesh.galav
  • 225
  • 1
  • 5
  • 17
  • 1
    With a custom validator you can run a single query to get all existing item_names and save it to a collection in a class property. you will need to add the new names on the go to the collection. – Gert B. Apr 19 '22 at 06:00
  • If you're validating CSV rows then maybe you should avoid using the `exists` rule and instead gather all names at the end and query the database in a single query to get all matching names and existing ids and manually reject rows that you can't find – apokryfos Apr 19 '22 at 06:29

1 Answers1

0

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');
       }
    });
}
Yogesh.galav
  • 225
  • 1
  • 5
  • 17