Extending Traits in PHP: A Pattern for Laravel SoftDeletes
You cannot technically "extend" a trait in the same way you extend a class using inheritance. Traits are not classes, and they do not have constructors or method resolution orders (MRO) that allow for a simple extends keyword. However, the goal of reusing logic while adding new behavior is a common requirement when working with packages like Laravel's SoftDeletes.
To achieve this, you must wrap the existing trait in a new one. This pattern involves creating a composite trait that includes all methods from the original and then adds your own functionality on top of them.
Wrapping the Original Trait
In your specific case, you want to build upon Illuminate\Database\Eloquent\SoftDeletes. The strategy is to create a custom trait that imports the base trait and then overrides or extends its methods.
Create a new file, perhaps named SaveWithHistory.php, within your app/Traits directory:
namespace App\Traits;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;
trait SaveWithHistory
{
// Import the original SoftDeletes functionality
use SoftDeletes;
/**
* Override the save method to handle history logic.
*/
public function save($guard = null)
{
$wasDirty = $this->isDirty();
if ($wasDirty && !empty($this->deleted_at)) {
// Logic to create a copy as a deleted record would go here
// This is where you might duplicate the model data before saving
// and set the new instance as "soft" deleted.
}
return parent::save($guard);
}
/**
* Add the new field that tracks who made the deletion.
*/
public function record_made_by_user_id()
{
// You can define getters/setters or use attributes here
// depending on how you intend to store this data.
return $this->attributes['record_made_by_user_id'] ?? null;
}
/**
* Override the delete method if needed to capture the user ID before deletion.
*/
public function delete()
{
// Capture the user performing the action before proceeding
$user = auth()->id();
return parent::delete();
}
}
Applying the Composite Trait
Once your new trait is defined, you apply it to your models alongside the original SoftDeletes trait. Note that since your new trait already uses SoftDeletes, you should not add use SoftDeletes; directly to your model again to avoid method conflicts or duplicate definitions.
class Product extends Model
{
use SaveWithHistory; // This implicitly includes SoftDeletes
protected $fillable = [
'name',
'record_made_by_user_id',
];
}
Understanding the Trade-offs
The primary advantage of this approach is encapsulation. You keep the original package's behavior intact while injecting your specific logic into the save and delete lifecycle hooks.
However, there are significant caveats to consider regarding method resolution order (MRO). When you use multiple traits that define methods with the same signature in a single class, PHP will throw an error if it cannot determine which version to call. By overriding the save and delete methods in your custom trait, you ensure that your specific logic runs before or after the parent logic as intended.
Be cautious when modifying the deleted_at attribute. If you attempt to set $this->deleted_at directly within an overridden method without understanding the internal state of the model, you might inadvertently trigger events like SoftDeletedEvent. Ensure your history copying logic handles transactional consistency correctly, perhaps by wrapping the copy and delete operations in a database transaction if they must happen atomically.
Conclusion
While you cannot strictly extend a trait, wrapping it is a robust pattern for extending functionality like SaveWithHistory. This approach allows you to maintain clean separation of concerns while leveraging existing libraries effectively. Just remember that every override introduces potential complexity in method resolution, so test the behavior thoroughly when applying these composite traits to your application's models.