简体   繁体   中英

Laravel Validation for UNIQUE values from table to put in error function(js)

Have a problem regards to validating values from looping. I get the values 'mobile_no' and 'email' from the loop to validate if those values are existing in my other table with the column of mobile no and email. Thankyou for any help.

   $get_values = DB::table('users_preview')->get();
   foreach($get_values as $values){
   $email = $values->email;
   $mobile_no = $values->email;

   /* now I want to validate if values of email and mobile no exist in 
      user's table , this is my sample way to do it which is actually 
      wrong*/

  // it only shows one validations but i like to show every each validations 
     for rows 
     if (users_preview::where('mobile', '=', $mobile_no)->count() > 0) {
            return response()->json([
                'message' => 'mobile is already 
                  exist', 
                'errors' => $numbers,
                'status' => false
            ]);
     } 


     }

     //scripts are 
     <script> 

    if(data.status == false){
    //some codes 
    }
    </script>

More convenient way than looping. In your model add a static function that will check if mobile exist:

class users_preview{
    static function mobileExist($value)
    {
        return users_preview::where('mobile', $value)
            ->count() != 0;
    }
}

Usage:

if(users_preview::mobileExist($mobile_no)){
    return 'Email has already exist';
}

Check and study also laravel validation which is relevant to your question.

First, it is not a good idea to query all rows on each request. Just imagine, if there are thousands of rows in yout table in future you will reach the max execution time wich defaults to 30 seconds. Second, this is no valid PHP code - just have a look to for rows and undefined variable $numbers . Third, a return statement ends script execution. If you like to get all existing values, you probably should return outside the loop.

Next thing, on top you are querying all records from table users_preview - and then your are checking against the same table, assuming users_preview is same to your eloquent model?

If your attempt is to check for duplicates in the whole table, please see this question on Stackoverflow: Finding duplicate values in a SQL table In Laravel you are able to execute raw statements by using users_preview::raw(" - MY STATEMENT - ")->get(); for example. Also users_preview::where('mobile', '=', $mobile_no)->count(); could be a possible solution for you. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM