Yogesh.galav
Yogesh.galav

Reputation: 295

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.

Upvotes: 0

Views: 363

Answers (1)

Yogesh.galav
Yogesh.galav

Reputation: 295

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');
       }
    });
}

Upvotes: 0

Related Questions