/** * @return ExportJob */ public function create() : ExportJob { $count = 0; while ($count < 30) { $key = Str::random(12); $existing = $this->findByKey($key); if (is_null($existing->id)) { $exportJob = new ExportJob(); $exportJob->user()->associate($this->user); $exportJob->key = Str::random(12); $exportJob->status = 'export_status_never_started'; $exportJob->save(); // breaks the loop: return $exportJob; } $count++; } return new ExportJob(); }