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
Using Traits in Laravel We have to evoke a new controller where we can assimilate the Traits, which will fetch all the records from the database. Generate a new controller using the below command. Insert following code in app/Http/Controllers/StudentController. php file to set the newly created Trait.
Helpers functions are used by the framework itself and also, you can use them in your own applications as per your convenience. Also, you can create custom helper functions. Traits are commonly utilized code. You can write a trait and can utilize it anywhere you desire.
It is a trait that links a Eloquent model to a model factory. Factories are normally used in testing when wanted test-data for a specific model. You can read more about factories in Laravel here: https://laravel.com/docs/9.x/database-testing#model-factories and here: https://laravel.com/docs/9.x/eloquent-factories.
Like traits for models should go in App/Models/Traits, for controllers in App/Http/Controllers/Traits and so.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With