Home » Php » php – Laravel Rule Validation Check Databse Not Working

php – Laravel Rule Validation Check Databse Not Working

Posted by: admin February 25, 2020 Leave a comment

Questions:

this is my code:

  $id_project = $request->id;
  $rfid       = $request->rfid;

  $validateData = $request->validate([
                    'name'      => 'required|string|max:255',
                    'rfid'      => 'required|min:40',[
                                    Rule::exists('usersdata')->where(function($query) use ($id_project,$rfid){
                                       $query->where('id_project', $id_project)->where('rfid', $rfid);
                                    }),
                    ],
                    'description'   => 'string|max:255|nullable',
                ]);

   $user = UserModel::create($validateData);
   return Response()->json(['success' => 'success insert data'], 200);

Validation for RFID (required or Min 40 char) its working.
but if i’m insert with same id_project and same RFID data that’s not working.
whereas in my database have already have id_project and rfid.
keep successful inserting data.

How to&Answers:

You have syntax fault on your code, compare your code with this corrected one:

$validateData = $request->validate([
    'name'      => 'required|string|max:255',
    'rfid'      => [
                       'required',
                       'min:40',
                       Rule::unique('usersdata', 'rfid')
                           ->where('id_project', $id_project)
                   ],
    'description'   => 'string|max:255|nullable',
]);