Do not remove data from the parent table while it is still being referenced in the child table

There are two tables in question - the Nationality table (parent) and the Employee table (child). The requirement is to display a message when a user attempts to delete data from the parent table that is currently being used by the child table. The message should state: "You cannot delete this record because it is being referenced by the employee table." While cascading delete can handle such actions, the intention here is not to delete the data unless it's not in use by the child table. An attempt has been made with the code provided below, however, only one ID from the table can be obtained. Assistance in resolving this issue would truly be appreciated.

An encountered error is as follows:

The issue arises where for the first user nationality ID, if the IF function passes successfully, it proceeds directly to the deletion section instead of displaying the desired warning message. Instead, it prompts the confirmation dialog box for deleting the data.

Code snippet from Nationality.vue file:

 <div class="card-body table-responsive p-0">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Nationality</th>
                  <th>Modify</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td colspan="3" align="center">
                    <p
                      v-if="Nationalities.data != undefined && Nationalities.data.length == 0"
                      class="text-center alert alert-danger"
                    >There is no data in the Table</p>
                  </td>
                </tr>
                <tr v-for="Nationality in Nationalities.data" :key="Nationality.id">
                  <td>{{Nationality.id}}</td>

                  <td>{{Nationality.nationality|UppCaseFirstLetter}}</td>

                  <!-- <td

                  >{{Nationality.nationality}}</td>-->

                  <td>
                    <a href="#" @click="editModal(Nationality)">
                      <i class="fa fa-edit"></i>
                    </a>|||
                    <a href="#" @click="deleteNationality(Nationality.id)">
                      <i class="fa fa-trash red"></i>
                    </a>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

Code from API routes:

Route::get('chekemployeeNationality','API\EmployeeController@chekemployeeNationality'); 

 Route::apiResources(['nationality'=>'API\NationalityController']);

Code from EmployeeController:

public function chekemployeeNationality()
{
    return Employee::all();
}

Code from Nationality Controller:

public function index()
    {
         return Nationality::orderBy('nationality', 'ASC')->paginate(5);
    }

Scripts section includes the following code:

export default {
  components: {
    Loading
  },
  data() {
    return {
      Nationalities: {},
      chekemployee: [],
      url: "api/chekemployeeNationality",
      form: new Form({
        id: "",
        nationality: ""
      })
    };
  },  
 methods: {
deleteNationality(id) {

      axios.get(this.url).then(response => {
        let data = response.data;

        data.forEach(element => {
          if (element.nationality_id == id) {
            toast.fire({
              type: "warning",
              title:

                "this id#" + element.nationality_id
            });
          } else {
            swal
              .fire({
                title: "Are you sure?",
                text: "You won't be able to revert this!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes, delete it!"
              })
              .then(result => {
                //Send request to the server
                if (result.value) {

                  this.form
                    .delete("api/nationality/" + id)
                    .then(() => {
                      swal.fire(
                        "Deleted!",
                        "Your file has been deleted.",
                        "success"
                      );
                      Fire.$emit("refreshPage");
                    })
                    .catch(e => {
                      console.log(e);
                    });
                }
              });
          }
        });

      });
},
loadNationalities() {
      if (this.$gate.isAdmin() || this.$gate.isUser()) {
        this.$Progress.start();
        axios
          .get("api/nationality")
          .then(({ data }) => (this.Nationalities = data));
        axios.get("api/employee").then(({ data }) => (this.employees = data));
        axios.get("api/chekemployeeNationality")
          .then(({ data }) => (this.chekemployeeNationality= data));

        this.$Progress.finish();
      }
    },
 created() {

    this.loadNationalities();

  }
}

Answer №1

At last, after 3 long days of searching, I have found the solution!

removeEmployee(id) {
      sweet
        .alert({
          title: "Are you absolutely certain?",
          text: "This action is irreversible!",
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Yes, delete it!"
        })
        .then(result => {
          //Sending request to server
          if (result.value) {
            this.employeeData
              .delete("api/employee/" + id)
              .then(() => {
                sweet.fire("Deleted!", "The selected file has been removed.", "success");
                Fire.$emit("updatePage");
              })
              .catch(e => {
                console.log(e);
              });
          }
        });
},
dismissEmployee(id) {
      this.records.forEach(entry => {
        this.list2.push(entry.nationality_id);
        if (this.list2.includes(id)) {
          notification.fire({
            type: "warning",
            title:
              "Unable to dismiss this employee as they have a connected nationality"
          });
        } else {
          this.removeEmployee(id);
        }

      });
    },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue slots in a loop to create a unique slider component

I'm struggling to figure out how to utilize slots for a SliderA component. The structure of SliderA component is as follows, with slides being an array prop. <template> <div class="slider-container" ref="container"> ...

Empowering Components with React Hooks

I am currently in the process of transitioning from using class components to React hooks with the Context API. However, I am encountering an error and struggling to pinpoint the exact reason for it. Here are my Codes: // contexts/sample.jsx import React ...

The android webview is having trouble loading HTML that includes javascript

I have been attempting to showcase a webpage containing HTML and JavaScript in an android webview using the code below. Unfortunately, it doesn't seem to be functioning properly. Can someone provide assistance? Here is the code snippet: public class ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

When attempting to achieve a CSS percent width, the output is given in pixels instead. I am in search of a solution where the percentage remains the same as the

My styling is set as a percentage, like this: <style> #somediv {width:70%} </style> <div id="somediv"></div> jQuery's css() function returns the result in pixels $(document).ready(function(){ var css = $("#somediv").css( ...

Wordpress database has been unexpectedly deleted

I'm in a bit of a pickle with my blog at the moment. The hosting company that manages my blog experienced some server issues, causing all MySQL Databases on the server to be lost (thankfully I had a backup from 2012). It never crossed my mind that the ...

I'm unsure of my recollection on how to utilize the /* syntax in JavaScript

Hey there, I'm facing a little issue. Can someone remind me how to correctly use the /* in JavaScript when dealing with URLs? For instance: if(URL == "www.thing.com/"){} I can't quite remember where to insert the /* so that it applies not just ...

I am unable to create a visual representation using the data obtained from the API

After utilizing Redux-Saga to fetch data from an API, I encountered difficulties accessing the updated state. This issue may stem from attempting to retrieve the data before it has been fully loaded into the redux state. //saga.js import axios from ' ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

How can Laravel 4's Eloquent be used to implement 'offset' instead of 'page' in the ->paginate() method?

Currently, I am in the process of transferring an existing REST API to Laravel 4.1, where the API relies on the offset querystring parameter to define the offset for the records. My aim is to utilize Eloquent's default paginate(), but it recognizes t ...

What is the best way to dynamically retrieve a URL and utilize it as a hyperlink using jQuery?

Is there a way to retrieve the current URL and use it as a link in jQuery? For example, if my browser is currently on page mysite.com/index.php?page=post&see=11, I would like to use this URL in my link and append /new/ after the domain name, like so: ...

When using Laravel, if the POST method redirects back to the form, simply refresh the page to display the "required error"

I am currently working on renaming URIs in my routes. While I am able to display the view, I encountered a problem when trying to save the data after hitting the button – the form reloads, resets, and the following errors are displayed within the form: ...

Tracking Clicks on Folders in jQuery File Tree

I am attempting to integrate a jQuery file tree into my website using the example provided below: Check out this jQuery file tree example While I can successfully trigger an event when a file is clicked, as demonstrated in the example, I am struggling to ...

Customizing buttons on Dialogs in JavaScript to have dynamic names

There is something on my website that resembles this: $("#id").html(msg2show).dialog({ //Other attributes buttons: { "Yes": function() {//Code}, "No": function() {//Code} } ...

Matching with Regex beyond the limits

Trying to extract a body tag using regex and then replace it with an appended string. However, encountering an issue where the regex is selecting more content than intended. regex: /<body.*[^>]>/i test string: <bla bla ><body class=&apo ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Automated resizing for various monitor dimensions in HTML

Is there a way to dynamically adjust the zoom level on an HTML webpage based on the monitor size? For instance, an image that appears large on a laptop screen may look small on a PC monitor. Is there a solution available to scale the picture size as the mo ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

What steps can I take to convert my React class into a function in order to incorporate Material UI components effectively?

With Emailjs set up successfully, my next step is integrating Material UI text fields (link: https://material-ui.com/components/text-fields/#text-field) to enhance the design of my project. The challenge I'm facing is incorporating Material UI classe ...

In JavaScript, how can we determine the structure of an object similar to the str function in R language?

One of the great features in R is the use of the str function, which allows you to examine the structure of an object. For example, you can use it to analyze the structure of a parsed json object like this (I'm using json as an illustration): txt = ...