Search code examples
laravellaravel-seedinglaravel-factory

Laravel Factory : How to make one field have content and the other one be null


I am creating a tag factory, and I want to it to either generate a project_tag_id or a gobal_tag_id but not both

return [
    'project_card_id' => ProjectCard::inRandomOrder()->first()->id,
    'user_id' => User::inRandomOrder()->first()->id,

    // to genreate project_tag_id or global_tag_id but not both
    'project_tag_id' => ProjectTag::inRandomOrder()->first()->id,
    'global_tag_id' => $this->faker->numberBetween(1,5),
  ];

Any help or insight on this would be much appreciated


Solution

  • Call a Random function if rand function return even insert project_tag_id else return global_tag_id so,

    $number=rand(0,10);
    if($number % 2 == 0){
      arr['project_tag_id'] => ProjectTag::inRandomOrder()->first()->id;
      arr['global_tag_id'] => null;
    }else{
       arr['project_tag_id'] => null;
       arr['global_tag_id'] => $this->faker->numberBetween(1,5);
    }