Is it possible to insert records if not exists and delete records if not provided in Laravel and MySQL?

Viewed 292

I have couple of checkboxes in my Laravel View lets say:

<input type="check" name="John">
<input type="check" name="Jane">
<input type="check" name="Mae">
<input type="check" name="Peter">

When I check all of the checkboxes, It will be save in the database like so:

#Participants Table
_____________
id  |  name
----+--------
 1  |  John
 2  |  jane
 3  |  Mae
 4  |  Peter

In my Log table:

#Log Table
_________________
id  |  activity
----+------------
 1  |  Added John as participant
 2  |  Added jane as participant
 3  |  Added Mae as participant
 4  |  Added Peter as participant

Now, my problem is when updating the participants.; In my Laravel view, I have all my checkbox selected based on the participants table data and let's say I unchecked John and Peter, When click update How can I add a history in my Log table that will display like this:

#Log Table
_________________
id  |  activity
----+------------
 1  |  Added John as participant
 2  |  Added jane as participant
 3  |  Added Mae as participant
 4  |  Added Peter as participant
 5  |  Removed John as participant
 6  |  Removed Peter as participant

and then in my Participants Table

#Participants Table
_____________
id  |  name
----+--------
 2  |  jane
 3  |  Mae

What I have done so far on Update:

$members = json_decode($request->projectmembers);
foreach ($members as $participantsitems) {
    DB::beginTransaction();
    DB::table('projects_participants')->upsert([
        'project_id' => $request->projectid,
        'task_id' => "",
        'emp_number' => $participantsitems->id,
        'created_by' => Auth::user()->emp_number,
        'date_created' => Carbon::parse(Carbon::now()),
    ],
    [
        'project_id' => $request->projectid, 
        'emp_number' => $participantsitems->id,
    ]);
    DB::commit();
    $this->record_project_history("Added ".$participantsitems->name ." as participant",$request->projectid, "");
}

But what it did was insert if record does not exists and update if record exists. can anyone give me an Idea on how to solve my problem? Thank you!

1 Answers

There's no direct why to do that. you should do this logic yourself.

But you there're some staff could help you (append to you method this snippet):

// after update/insert your new data you will need to delete other records
// using updated_at column to delete all records updated a second ago
// make sure to create a model for projects_participants and use it all over your code
ProjectsParticipant::where('project_id', $request->projectid)
->where('updated_at', '<=', Carbon::now()->subSecond())->delete();
Related