Home > Net >  How to test autogenerate field is unique in Laravel
How to test autogenerate field is unique in Laravel

Time:11-26

I would would like to know if this is the best way to test if an autogenerated field is unique: This is my Project Model:

public function generateShortUrl(): void
{
   $this->short_url = $this->randomString();
   $this->save();
}

public function randomString(): string
{
   $alphaString = collect(range('A', 'Z'))
       ->shuffle()
       ->take(5)
       ->implode('');

   if ($this->checkShortUrlExists($alphaString)) {
      return $this->randomString();
   }

   return $alphaString;
}

public function checkShortUrlExists($alphaString): bool
{
   if ($this->where('short_url', $alphaString)->exists()) {
       return true;
   }    
   return false;
}

and this is my test:

public function test_short_url_must_be_unique()
{
   $project = Project::factory()->create([
      'short_url' => 'QWQWQ'
   ]);       

   $this->assertTrue($project->checkShortUrlExists('QWQWQ'));
}

CodePudding user response:

Your solution seems to be okay-ish. But it could lead to huge loops, as there are not so many combinations available with 5 letters (and "expensive" as you query the DB on every loop for existence check).

You could use something like UUIDs to generate unique identifiers.

You could also use a "slug" system that takes care of duplicates for you.

  • Related