0

I'm not sure if I explained briefly what's the problem is about. I have a user voting form in which user passes his first name,surname,mothers' surname, and ID.

I have also a table users which stores all this data. Yesterday I found a bug or I misunderstood how laravel validation works because it passes submit every time when it find all the data existing in table.

This is a table with two records.

EXAMPLE

What i expected from validation was to check if the ID=98111091239 name=Andrzej surname=Pianowski and mother surname =Mila and only if everything is correct and exists in one row then the vote can be made.

Instead i can pass ID from first row, other things from second and it also will allow user to vote. Is that a bug, laravel works that way or what? I'm really looking forward for any tip,help,sugestions.

enter image description here

And here's validation rule i'm using

  /*This validates whether all data is correct  */
   $validator = Validator::make($request->all(),[
   //check whether such pesel exists in votes and in voters
       'pesel' =>'required|exists:wyborca|max:11|min:11',
       'imie' =>'required|exists:wyborca|max:64|min:2',
       'nazwisko' => 'required|exists:wyborca|max:128|min:2',
       'nazwisko_matki' => 'required|exists:wyborca|max:128|min:2'
       ]);
  if($validator->fails())
  {
    return back()
      ->with('errors','Wprowadzono nieprawidłowe dane')
      ->withInput();
  }
Nathan Siafa
  • 731
  • 4
  • 19
  • 39
Wini the Pooh
  • 383
  • 1
  • 5
  • 20
  • Possible duplicate of [Laravel validation: exists with additional column condition - custom validation rule](https://stackoverflow.com/questions/26121417/laravel-validation-exists-with-additional-column-condition-custom-validation) – Maraboc Jul 11 '17 at 19:58
  • Nope,it's different topic – Wini the Pooh Jul 11 '17 at 20:23

1 Answers1

1

The validator seems to be passing since those values probably exist in multiple records and not just a single one.

One solution would be to validate to ensure that all the fields are present in the request and then do a simple Eloquent query to check if the record exists:

$user = App\User::where('id', $request->id)
    ->where('name', $request->name)
    ->where('surname', $request->surname)
    ->where('mother', $request->mother)
    ->exists(); //true or false

if($user){
//vote
}

return response()->json(['error' => 'user not found'], 404);

If it does exist, cast the vote else return an error.

Yat23
  • 181
  • 4