6

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

9
  • Does it show any errors? Commented Jun 27, 2018 at 9:59
  • @Script47, check updated, thx.:) Commented Jun 27, 2018 at 10:03
  • you must have an error in namespace Commented Jun 27, 2018 at 10:03
  • 1
    Traits are like class mixins. No class means no trait Commented Jun 27, 2018 at 10:09
  • 1
    in other words: what does $this refer to in your code? Commented Jun 27, 2018 at 10:14

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.