Hello I'm creating a Factory for a discount model. I have two fields ('original_price' and 'discounted_price'). I'm using randomFloat in factory to create a random number with 2 decimals for the 'original_price'. How can I set 'discounted_price' to be always a lower value than 'original_price'?
At the moment 'discounted_price' has the same faker value than 'original_price' because I cant find a way of doing this.
<?php
namespace Database\Factories;
use App\Models\Category;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Discount>
*/
class DiscountFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'user_id' =>User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence(),
'slug' => $this->faker->slug(),
'body' => '<p>' . implode('</p><p>', $this->faker->paragraphs(6)) . '</p>',
'original_price' => $this->faker->randomFloat('2',0,2),
'discounted_price' => $this->faker->randomFloat('2',0,2),
];
}
}
I think I came across a solution but I dont know if this would be right. My idea is that the minimum value of 'discounted_price' should be 50% of 'original_price' and the maximum should be 'original_price' - 5. Would this be the correct way of doing it?
<?php
namespace Database\Factories;
use App\Models\Category;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Discount>
*/
class DiscountFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'user_id' =>User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence(),
'slug' => $this->faker->slug(),
'body' => '<p>' . implode('</p><p>', $this->faker->paragraphs(6)) . '</p>',
$original_price = 'original_price' => $this->faker->randomFloat('2',0,2),
'discounted_price' => $this->faker->numberBetween($min=$original_price/2, $max=$original_price-5)
];
}
}
CodePudding user response:
Seems about right, I would advise you to not mix and match property assignment in the array values to keep things clear
public function definition()
{
$originalPrice = $this->faker->randomFloat('2', 0, 2);
$discountMin = $originalPrice / 2;
$discountMax = $originalPrice - 5;
return [
'user_id' =>User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence(),
'slug' => $this->faker->slug(),
'body' => '<p>' . implode('</p><p>', $this->faker->paragraphs(6)) . '</p>',
'original_price' => $originalPrice,
'discounted_price' => $this->faker->numberBetween($discountMin, $discountMax)
];
}