Laravel – Execute Trait Code in Tinker

  • Post category:Snippets

If you want to execute code from a trait when using php artisan tinker, you can do so in one of two methods.

1] Instantiate the class using the trait and use it via that:

// Class using your trait
class MyClass {
    use MyTrait;
}
PHP

$myObject = new MyClass;

$myObject->codeFromTrait();
php artisan tinker

2] Create an anonymous class to use the trait in Tinker directly

$object = new Class { use App\Traits\MyTrait; };

$object->codeFromTrait();
php artisan tinker