eskimo
eskimo

Reputation: 2625

Call Trait method inside model event closure

This throws an error:

use App\Traits\Test;

class Post extends Model {
    
    use Test;

    static::updated(function ($product) {
        $this->foo();
    });
}

In App\Traits\Test

trait Test {
  private function foo() {
    ...
  }
}

How can I use foo() from the trait Test in the Post model event closure?

Upvotes: 1

Views: 1098

Answers (1)

Donkarnash
Donkarnash

Reputation: 12845

To use instance methods inside static class methods is not permissible. It will throw an error "Using $this in static context"

So there are two options

use App\Traits\Test;

class Post extends Model 
{
    
    use Test;

    static::updated(function ($product) {
        $instance = new static;
        $instance->foo();
    });

    //...
}


namespace App\Traits;

trait Test 
{
    private function foo() 
    {
      ...
    }
}

OR declare the method as static method in the trait


use App\Traits\Test;

class Post extends Model 
{
    
    use Test;

    static::updated(function ($product) {
        static::foo();
    });

    //...
}



namespace App\Traits;

trait Test 
{
    private static function foo() 
    {
      ...
    }
}

There's also an option to boot the trait and hook into the boot method of trait to define model events in a trait - for that a static method with public visibility must be defined in the trait following the convention of bootNameOfTrait

namespace App\Traits;


trait Test 
{

    public static function bootTest()
    {
        static::updated(function($product){
            static::foo();
            //other processing as if defined on model class
        });
    }

    private static function foo() 
    {
      ...
    }
}


use App\Traits\Test;

class Post extends Model 
{
    
    use Test;

}

Upvotes: 2

Related Questions