Is there a way to extend a trait in PHP?

Yevgeniy Afanasyev picture Yevgeniy Afanasyev · Oct 28, 2016 · Viewed 21.8k times · Source

I want to use functionality of an existing trait and create my own trait on top of it only to later apply it on classes.

I want to extend Laravel SoftDeletes trait to make SaveWithHistory function, so it will create a copy of a record as a deleted record. I also want to extend it with record_made_by_user_id field.

Answer

Filip Koblański picture Filip Koblański · Oct 28, 2016

Yes, there is. You just have to define new trait like this:

trait MySoftDeletes 
{
    use SoftDeletes {
        SoftDeletes::saveWithHistory as parentSaveWithHistory;
    }

    public function saveWithHistory() {
        $this->parentSaveWithHistory();

        //your implementation
    }
}