Home » Php » php – Laravel – Is it possible to replace/extend a trait from within Laravel core?

php – Laravel – Is it possible to replace/extend a trait from within Laravel core?

Posted by: admin February 25, 2020 Leave a comment

Questions:

Is this possible? I am using a multi-tenancy package that conflicts with other Laravel packages such as Scout. Ideally I want to be able to replace/extend the Illuminate\Queue\SerializesModels trait within the core.

Obviously the other way to do this is just replace that trait with my own one in every job that runs, but it does then mean in the case of things like Laravel Scout I have to rewrite the scout classes, just to replace this one trait, within my own app which feels wrong.

As an example, Laravel Scout has the MakeSearchable job class. In order to replace the trait in this model I have to make my own implementation of the class which is identical to the package apart from changing this one trait:

class MyMakeSearchable implements ShouldQueue
{
    use TenantAware, Queueable, MySerializesModels;

    /** @var Collection */
    public $models;

    public function __construct($models)
    {
        $this->models = $models;
    }

    public function handle()
    {
        if (count($this->models) === 0) {
            return;
        }

        $this->models->first()->searchableUsing()->update($this->models);
    }
}

To connect up this job class, I then have to override the Scout Searchable trait too.

It would be nice if I could just say to Laravel “Whenever you want this SerializesModels trait, use this one instead`

How to&Answers: