Deleting associated records in LaravelLaravel gives you the ability

Managing soft deletion of departments when a company is soft deleted can be tricky. The current implementation involves iterating through each department associated with the company and soft deleting them. However, it seems that only the first department is being successfully soft deleted even though there are more departments in the company.

In the Company.php file, the code snippet for handling soft deletion of departments within the 'deleting' event is provided:

protected static function boot()                         
{                                                        
    parent::boot();                                      
    static::deleting(function($company) {                
        foreach($company->department as $department)     
        {                                                
            $department->delete();                       
        }                                                
    });                                                  
}   

The above code executes soft deletion for each department linked to the company. However, if this is not working as expected, it might be due to how relations are defined or another underlying issue.

An additional consideration is the relationship between departments and employees. It is mentioned that departments have many employees, which adds complexity to the soft deletion process. For soft deleting all employees related to a specific department, a similar approach is taken within the 'deleting' event in the Department model:

protected static function boot()
    {
        parent::boot();
        static::deleting(function($department) {
            Employee::where('DepartmentId','=',$department->DepartmentId)->delete();
        });
    }       

Answer №1

Check out this solution:

$deptIDs = Department::where('company_id', '=', $comp->id)->select('id')->distinct()->get()->toArray();
Department::where('company_id', '=', $comp->id)->delete();

DB::table('users')->whereIn('department_id', $deptIDs)->delete();

Give it a try and let me know if it works for you.

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

Update the configurable product process for the custom attribute 'delivery_time' in Magento 1.9.2

I am currently using Magento 1.9.2.4 (1.9.2.3 in my Testpage) and I have a few configurable products with multiple options. Each product (child of the configurable one) has a different delivery time. To achieve this, I created an attribute called "delivery ...

PHP web application experiencing delays in response time following the execution of a PowerShell script

I'm currently developing a PHP web application on an IIS web server, and my goal is to create a read-only PowerShell live web console. Here's how the setup works: 1) On the main "console" page, there is a div element along with some buttons. I ...

Extract and display the custom file's output using shell_exec function in PHP

Is there a way to view the output of a shell script in a format similar to PuTTy or gnome-terminal using a php script? I attempted to use shell_exec with the following invocation: $output = shell_exec('echo "return value: ";foo=$(nameOfFileToExecute) ...

Basic jQuery fetch request

Having some trouble implementing an onclick button to send a get request to a php file. The jQuery is loading correctly, so that's not the issue. Check out the code below: The function that needs to be called <script type='text/javascript&a ...

What causes the white screen issue when utilizing Inertia in Laravel for page rendering?

The technologies I'm working with are: Laravel, Inertiajs, and Vue.js. Although I am new to using Laravel, I encountered an issue when running composer require laravel/breeze --dev and php artisan breeze:install vue which resulted in my Laravel proj ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

Using jQuery Datepicker Beforeshowday to dynamically retrieve an array of unavailable dates through Ajax

Currently, I am working on implementing a datepicker that will update an array of unavailable dates. While it successfully works with a PHP variable being passed, the challenge lies in properly returning the data for the option (as it is throwing a console ...

Set default values for input fields based on selected options in php and mysql

I need help creating a form that will submit details when an option is selected from a database. The MySQL table has the following fields under USERS : [email], [age], [name]. I want to automatically fill in the values of other input fields when a user s ...

I am attempting to establish a connection to a database using PDO within the CodeIgniter framework

$database_config = array( 'hostname' => 'mysql:host=myhostname;dbname=test;', 'username' => 'root', 'password' => '', 'database' => 'test', &apo ...

I am having difficulty retrieving information from the Laravel API

I am struggling to retrieve data from my Laravel application and display it in Vue CLI. While I can see the response, I am encountering difficulties when trying to show it in the Vue application. https://i.stack.imgur.com/tCgrd.png Whenever I attempt to f ...

Is there a way to update a variable in a controller using AJAX?

Is it possible to update a variable in the controller using Ajax? Controller: $basl = array(2018,11,18,0,0); $deger = 3; $baslamatarihi=Carbon::create($basl[0],$basl[1],$basl[2],$basl[3],$basl[4]); $bitistarihi = Carbon::create($basl[0],$basl[1],$basl[2] ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Trouble with using AJAX to transfer a JavaScript variable to a PHP file

I need assistance in sending a JavaScript variable to a PHP file for displaying comments on a webpage. While I have successfully sent the JS variable to other PHP files, I'm facing issues when trying to do the same with the comment-list.php file. It ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Manipulating text columns in SQL tables using PHP to convert them into clickable URLs

I have a column in my database that stores the top gaining athletes on my fantasy sports website. I want to make each athlete's name a clickable link that directs users to their individual page on our site. Currently, the function in the code is calli ...

Mastering the art of displaying a progress bar using ajax, php, and mysql

I am facing an issue with querying a large amount of data from the database and displaying a progress bar. Even though my code successfully retrieves data from the server, the progress bar immediately jumps to 100% without updating while the Ajax query is ...

Is there a way to determine if a button was clicked using twig?

I need assistance with implementing a button in my twig file within a table that will remove an element from an array. Ideally, I would like to remove the element based on its index. From the research I have conducted, it seems that data manipulation shou ...

What is the best way to retrieve the previously chosen value from one dropdown and populate it into another dropdown when

I have 3 choices available. When the user selects the third option, a jQuery onchange event is triggered to send the variable to another PHP file for database validation based on the selected id. The challenge lies in how I can also include the variables f ...

Can you explain the distinction between X-XSRF-TOKEN and X-CSRF-TOKEN?

What is the difference between using a hidden field and a header in web development, and why would you choose one over the other? When do we use X-XSRF_TOKEN? And when do we use X-CSRF TOKEN? ...