Уникальное значение текстового поля в Laravel, vuejs, Axios, JavaScript - PullRequest
0 голосов
/ 09 ноября 2019

Я хочу, чтобы всплывающее сообщение toastr отображалось, когда пользователь пытается вставить дублирующее значение для BageCode в форме, если кто-нибудь может мне помочь, это будет так любезно с его стороны. Если проверка столбца остальных форм работает, тостер работает, но я не знаю, как сравнить данные из базы данных и данные в форме, подобной этой

if (this.form.BadgeCode == data.BadgeCode) {toast.fire ({type: "warning", title: "Код значка уже взят."});}

Код в EmployeeController:

public function index()
    {
        $date=\Carbon\Carbon::today();
        //  $this->authorize('isAdmin');
        $employee=Employee::where('expiredate','>',$date)->paginate(5);
    // return Employee::all();
    return response()->json($employee);
   }


public function store(Request $request)
        {

        //    $this->authorize('isAdmin');
            $this->validate($request,[           
                // 'BadgeCode'=>'required|string',  
               'BadgeCode'=>'required|unique:employees,BadgeCode',
                'BadgeType'=>'required', 
     ])             'company_id'=>'required',
    }

Код в маршруте API:

Route::apiResources(['employee'=>'API\EmployeeController']);

Код в Employee.vue:

   <div
      style="width:45%;margin-left: 35%;"
      class="modal fade"
      id="addNew"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNewLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" v-show="!editMode" id="addNewLabel">Add New employee</h5>
            <h5 class="modal-title" v-show="editMode" id="addNewLabel">Update employee's Info</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <form
            @submit.prevent="editMode ? updateemployee() : createemployee()"
            enctype="multipart/form-data"
          >
            <div class="modal-body">
              <div class="form-group">
                <select
                  name="company_id"
                  id="company_id"
                  :class="{'is-invalid':form.errors.has('company_id')}"
                  class="form-control"
                  v-model="form.company_id"
                >
                  <option value selected>Select Company</option>
                  <option
                    v-for="Company in Companies"
                    :key="Company.id"
                    :value="Company.id"
                  >{{Company.Company}}</option>
                </select>
                <has-error :form="form" field="company_id"></has-error>
              </div>
              <div class="form-group">
                <input
                  v-model="form.BadgeCode"
                  placeholder="Enter BadgeCode"
                  type="text"
                  name="BadgeCode"
                  class="form-control"
                />
                <!-- :class="{ 'is-invalid': form.errors.has('BadgeCode') }" -->
                <!-- <has-error :form="form" field="BadgeCode"></has-error> -->
              </div>

              <div class="form-group">
                <select
                  name="BadgeType"
                  v-model="form.BadgeType"
                  id="BadgeType"
                  class="form-control"
                  :class="{'is-invalid':form.errors.has('BadgeType')}"
                >
                  <option value selected>Select BadgeType</option>
                  <option value="Resident">Resident</option>
                  <option value="Non-Resident-Expat">Non-Resident Expat</option>
                  <option value="Non-Resident-LN">Non-Resident LN</option>
                  <option value="Baron-employee">Baron-employee</option>
                </select>
                <has-error :form="form" field="BadgeType"></has-error>
              </div>

            </div>
          </form>
        </div>
      </div>
    </div>

Код в сценарии:

<script>

export default {
  // el: "#wrapper2",


  data() {
    return {          
      seen: false,
      seen2: true,
      color: "blue",
      size: "20px",
      editMode: false,
      Companies: {},
      employees: {},
      form: new Form({
        id: "",
        BadgeCode: "",
        BadgeType: "",
        company_id: "",

      })
    };
  },
  methods: {


    getvalidateion() {
      axios.get("api/employee").then(response => {
        let data = response.data.data;


        if (data) {
          data.forEach(element => {
            if (this.form.BadgeCode == data.BadgeCode) {
              toast.fire({
                type: "warning",
                title: "The badge code has already been taken."
              });
            }
          });
        } else {
          console.log("NO DATA");
        }
      });
    },
    createemployee() {
      this.getvalidateion();
      if (this.form.company_id == "") {
        toast.fire({
          type: "warning",
          title: "Please Select the Company."
        });
      } else if (this.form.BadgeCode == "") {
        toast.fire({
          type: "warning",
          title: "BadgeCode is required."
        });
      } else if (this.form.BadgeType == "") {
        toast.fire({
          type: "warning",
          title: "Please Select the BadgeType."
        });
      } else if (this.form.nationality_id == "") {
        toast.fire({
          type: "warning",
          title: "Please Select the Nationality."
        });
      } else if (this.form.expiredate == "" || this.form.issuedate == "") {
        toast.fire({
          type: "warning",
          title: "Please fill the issuedate or expiredate fileds ."
        });
      } else if (this.form.photo.length == "") {
        toast.fire({
          type: "warning",
          title: "Please select photo."
        });
      } else if (
        this.form.afghanidatephoto != undefined &&
        this.form.afghanidatephoto.length == ""
      ) {
        toast.fire({
          type: "warning",
          title: "Please select AfghaniDate."
        });
      } else {
        this.form
          .post("api/employee")
          .then(() => {
            //    the below function will be use to reload the page

            //   this.$emit("refreshPage");
            $("#addNew").modal("hide");
            toast.fire({
              type: "success",
              title: "employee Created successfully"
            });

            this.form.reset();
            $("#afghanidatephoto").val("");
            $("#photo").val("");
            Fire.$emit("refreshPage");

          })
          .catch(e => {

            console.log(e);
          });
      }
    },



  created() {
    Fire.$on("searching", () => {
      let query = this.$parent.search;
      axios
        .get("api/findemployee?q=" + query)
        .then(data => {
          this.employees = data.data;
        })

        .catch(() => {});
    });
    this.loademployees();
    this.getvalidateion();
    // load the page after 3 secound
    Fire.$on("refreshPage", () => {
      this.loademployees();
    });
  }
};
</script>

Код в модальном:

 $table->string('BadgeCode')->unique();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...