Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : Delete all records that are not in array

I have a datepicker calendar in my views, and basically I need to synchronize the selected dates (that I send in ajax) with a BoxDeliveryDate model (which only has one column named "date").

So in my Controller I was able to write a pretty nice method to only create a new record if one the selected dates is not yet stored in the database, like this :

foreach (Request::get('dates') as $date) {
        $date_formated = date('Y-m-d', strtotime($date));
        BoxDeliveryDate::firstOrCreate(['date'=>$date_formated]);
    }

Now, if the user de-select one the dates in the datepicker, later, and synchronize, I need to delete it from the database.

Is there a nice way to do that in Laravel ? In other words, to delete every record of the table that are NOT in my Request::get('dates') ?

Also, I searched for a simple way to synchronize everything with only one method, but couldn't find anything.

Thanks for helping !

like image 862
Clément Rigo Avatar asked Apr 08 '15 09:04

Clément Rigo


People also ask

How do I delete all records in laravel?

In the first example, we are going to use the truncate() function, which is used to delete all the records. In the second example, we will delete records on the basis of the id. So we will specify some id and use the delete() function to delete all the records of that particular id.

How do I delete specific data in laravel?

Step 1: Create Controller UserController by executing this command. Step 2: We can delete records in two ways. Second Method: The second way is to delete using the Laravel delete Function and User Model (Easy one). ->name( 'users.

How do you delete in laravel eloquent?

Laravel Eloquent Deleting You can delete data after writing it to the database. You can either delete a model instance if you have retrieved one, or specify conditions for which records to delete. To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete();


Video Answer


1 Answers

You can use whereNotIn() for that:

BoxDeliveryDate::whereNotIn('date', Request::get('dates'))->delete();

Note that this will not trigger any model events nor will it work with soft delete. Also, depending on the format of dates you might have to format the array before passing it to whereNotIn().

Also I believe it should be Request::input('dates') but it's possible that both actually works...

like image 74
lukasgeiter Avatar answered Sep 20 '22 21:09

lukasgeiter