Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions app/Certificate.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,14 @@ class Certificate extends Model
'name',
'abbreviation',
];

public static function booted(){
static::deleted(function($certificate){
$certificate->users()->detach();
});
}
Comment on lines +17 to +20

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this defeats most of the purpose of using soft deletes for this model. After all, the certificate itself consists merely of a name and abbreviation. The most valuable certificate data lies in its relations, i.e., which users the certificate is/was assigned to.

In Laravel, soft deletes behave the same as actual deletes, unless the deleted records are explicitly requested using ->withTrashed(). Note that this allows us to keep the "pivot rows" of removed certificates while automatically hiding them when not requested. This makes restoring accidental deletes possible.


Observe that the certificate BelongsTo relation on the User model explicitly requests the certificates withTrashed:

return $this->belongsToMany(Certificate::class)
->withTimestamps()->withTrashed();

In case we want to exclude removed certificates from the user's certificate overview (which IMO we do), we should simply remove the ->withTrashed() from that line. That would remove the need to detach on delete as well as the migration.


public function users(){
return $this->belongsToMany(User::class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
DB::table('certificate_user')->
where('certificate_id', function ($query) {
$query->select('id')->from('certificates')->whereNotNull('deleted_at');
})->delete();
}

/**
* Reverse the migrations.
*/
public function down(): void
{
//
}
};
Loading