How to generate and Insert millions of random numbers and save in a database in Laravel
I am currently working on a Laravel Application and it has a feature where some certain users will login to generate unique 12 digits unique PIN numbers.
Users with certain privileges should be able to generate minimum of 1000 or 10,000 PINS in one request.
I am presently doing this, which is inefficient as its very costly to server resources :
class PinController extends ApiController
{
public function __construct(Auth $auth, Pin $pin){
$this->auth = $auth;
$this->pin = $pin;
$this->middleware('jwt.auth', ['except' => ['index','show']]);
}
//pin generator - works
protected function random($length = 14)
{
$pool = '123456789';
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length - 2);
}
public function store(StoreRequest $request)
{
$number_of_pins = $request->get('number_of_pins');//say 10000
$user = $this->auth->user();
$numbers =[];
for($i=0; $i <= $number_of_pins; $i++){
$number = $this->random(); //generate random 12 digit pins
$numbers[] = $number;
if(!in_array($numbers, $number) || !$this->pin->where('number',$number)->get())
{
$this->pin->create(['number'=>$number,'user_id'=>$user->id]);
}else{
$i--;
}
}
}
}
This takes a very long time to execute and fails all the time. I am considering using queue jobs do this in chucks but I might not be the best solution for my app's feature.
Any suggestion on best way to do this will be appreciated.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire