Home > Net >  Laravel: a given number of models (download codes) in a single controller method
Laravel: a given number of models (download codes) in a single controller method

Time:08-14

I am building a feature which generates a given number of download codes and popupates the DB table with them. So with this link downloadcodes/generate/10?type=1 I want to create 10 entries in my table.

The controller method looks like this:

    public function generate($quantity)
    {


        $codetype = Input::get('type');

        
        XXXX{    // ITERRATING LOOP from 1 to 10 

            $object = new DownloadCode;

            $object->type = $codetype; 
            $object->code = [string-of random-6-digits];
            $object->save(); 

        }

        return $quantity. " codes generated". $codetype;

    }

Thank you.

CodePudding user response:

First, you need to receive this number with a variable inside the route

Route::get('generate/{entries}','YourController@generate');

You can send it as follows

{{route('path.to.route.generate', 10)}}

Then you can insert that into a loop

public function generate($quantity , $entries)
{

    $codetype = Input::get('type');

    
    for($i = 0; $i < $entries; $i  ) {    
        $object = new DownloadCode;

        $object->type = $codetype; 
        $object->code = [string-of random-6-digits];
        $object->save(); 
    }


    return $quantity. " codes generated". $codetype;

}
  • Related