Undefined variable: error in Laravel 5.6

I have controller to input data to database and show error if duplicate data but i get message

Undefined variable: error

$cek = DB::table('peserta')->where('email',$email)->count();
  if ($cek > 0 and count($error) > 0 ) {
    $pesan = [];
    $pesan['halu'] = 'danger';
    $pesan['message'] = 'Email anda sudah terdaftar';
  }

3 answers

  • answered 2018-07-11 03:02 Jay Are

    your variable $error is undefined. Meaning, somewhere in your code, the variable $error is not assigned to any value, check your line 2 near count($error).

  • answered 2018-07-11 03:54 Mahmudul Hasan

    variable $error is undefined. Because you used $error, but you are not declared $error before "if ($cek > 0 and count($error) > 0 )" this line. and this $error needs array type data. becouse, count() expect array type data.

    i think your code like :

    $cek = DB::table('peserta')->where('email',$email)->count();
    $error = your own errors array;
      if ($cek > 0 and count($error) > 0 ) {
        $pesan = [];
        $pesan['halu'] = 'danger';
        $pesan['message'] = 'Email anda sudah terdaftar';
      }
    

  • answered 2018-07-11 06:22 DigitalDrifter

    You're making it harder than necessary:

    if (DB::table('peserta')->where('email',$email)->exists()) {
        // email exists...
    } else {
        // email doesn't exist...
    }