I'm working with relationships with Laravel 5.2 and Eloquent but I have not been able to find a way to soft-delete relationship records (a.k.a Pivot records). My specific case is:
I Have a Company model and I also have a Person model. I simply want to relate one or more Person records with a Company using the "employees" table. That table has some fields including the "deleted_at" field (added through a migration script).
I can get the employees() records thanks to the belongsToMany definition:
public function employees() {
return $this->belongsToMany(Person::class, 'employees')
->withPivot(['start_date', 'end_date'])
->withTimestamps();
}
But whenever I try to detach() or even delete() one of the pivot records, I see the actual record is deleted from the database:
$employee = $companyRecord->employees()->wherePivot('person_id', $person_id)->first();
$employee->pivot->delete(); // The relationship record in 'employees' table is removed completely.
I want to soft-delete those Pivot records because I need to be able to get them back later if I want to know who worked for that company in the past, and how long did that person last in that company, and perhaps some other reference details.
I've seen the possibility to override the newPivot method on the Company and Person models, and the creation of certain Pivot class by extending the "Illuminate\Database\Eloquent\Relations\Pivot" class (see here [https://softonsofa.com/laravel-custom-pivot-model-in-eloquent/]) but that method does not seem to work for detach/delete/sync methods, only for reading operations...
Laravel documentation also lacks of information about the possibility of soft-deleting pivot records. I've seen some other examples where the belongsToMany relationship is defined in a way that it retrieves records with "deleted_at IS NULL" only, but I want to be sure that there is not a Laravel-way to do that already.
Thanks for any help.