简体   繁体   中英

how to add validate rules

I tried to add unique validation rule in controller. but why the duplicate data still record to database.

Controller

public function tambahDataWNI(Request $request){
    $validation = $request->validate([
        'no_identitas' => 'required|unique:pendataan,no_identitas'
    ]);

    $c = new InputdatawniModel();
    $c->jenis_identitas = $request->jenis_identitas;
    $c->no_identitas = $request->no_identitas;
    $c->nama = $request->nama;
    $c->asal_shelter = $request->asal_shelter;
    $c->save();

    return redirect('inputdatawni');
}

take a look on here unique rules

based on that reference you need to make sure that you use correct table name and correct column name

$validation = $request->validate([
    'no_identitas' => 'required|unique:table_name,column_name'
]);

Make sperate request file for this

 public function rules()
{
    switch ($this->method()) {
        case 'POST':
        return [
            'no_identitas' => 'required|unique:tablename,columnname,NULL,id,deleted_at,NULL',
        ];
        case 'PUT':
            $model = Model::whereId($this->model)->first();

        return [

        'no_identitas' => 'required|numeric|unique:tablename,name,' . $model->id . ',id',deleted_at,NULL',

        ];
        default:
        break;
    }
}

Add Below validator class in your controller.

use Illuminate\\Support\\Facades\\Validator;

And Check with below code.

$validator = Validator::make($request->all(), 
         [
            'no_identitas'=>'required|unique:your_tablename'
         ]);

if($validator->fails())
{
   // Error if any
}else{
  // No Errors
}

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