6
votes

If Model factroy is as below then how to use Trait getData() in here?

This code not worked.

<?php

use App\Working;
use App\Traits\Calculate;

...

    $factory->define(App\Working::class, function  (Faker\Generator $faker) {        
       ...    
       $getData = $this->getData();        
       ...     
       return['get_data' => $getData];

    }

Error message:

Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined method Illuminate\Database\Eloquent\Factory::getData()

Exception trace:

1 Illuminate\Database\Eloquent\Factory::{closure}(Object(Faker\Generator), []) G:\test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:263

2 call_user_func(Object(Closure), Object(Faker\Generator), []) G:\test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:263

1
Does it show any errors?Script47
@Script47, check updated, thx.:)JsWizard
you must have an error in namespaceAdnan Mumtaz
Traits are like class mixins. No class means no traitapokryfos
in other words: what does $this refer to in your code?nozzleman

1 Answers

10
votes

Probably not what you're looking for but here goes:

You can create an inline class that defines a function that returns the real function you want to use. That inline class can use a trait.

Note: Anonymous classes were added in PHP 7

<?php

use App\Working;
use App\Traits\Calculate;

// ...
$factory->define(App\Working::class, (new class {
     use Calculate;
     public function generatorFunction() {
         return function (Faker\Generator $faker) {
             // ...
             $getData = $this->getData();
             // ...
             return ['get_data' => $getData];

         };
     }
 })->generatorFunction());

Update:

Since Laravel 8 model factories are now classes instead of functions so can use traits making the above solution unnecessary.