Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon how do I integrate calculated fields with Laravel's factory system
    Laravel factory system calculated fields afterCreating method Eloquent BMI calculation


how do I integrate calculated fields with Laravel's factory system


To integrate calculated fields with Laravel's factory system, you can use the `afterCreating` method in your factory to calculate the calculated field after the model is created. Here is an example:

php
use App\Models\Profile;
use Illuminate\Database\Eloquent\Factories\Factory;

class ProfileFactory extends Factory
{
    protected $model = Profile::class;

    public function definition()
    {
        return [
            'user_id' => factory(User::class),
            'weight' => $this->faker->randomNumber(3),
            'height' => $this->faker->randomNumber(3),
            'dob' => $this->faker->date,
        ];
    }

    public function afterCreating(Profile $profile)
    {
        $profile->bmi = $profile->weight / ($profile->height * $profile->height);
    }
}

In this example, the `afterCreating` method is called after the `Profile` model is created. It calculates the `bmi` field based on the `weight` and `height` fields.

Citations:
[1] https://stackoverflow.com/questions/49179477/calculated-fields-in-database-laravel
[2] https://laracasts.com/discuss/channels/laravel/what-is-the-best-practice-to-save-a-calculated-field-with-laravel
[3] https://laracasts.com/discuss/channels/eloquent/calc-field-in-laravel
[4] https://stackoverflow.com/questions/38113598/add-a-calculated-field-to-laravel-model-query
[5] https://laracasts.com/discuss/channels/laravel/how-to-add-calculated-fields-to-an-eloquent-resource