Maks.Burkov
Maks.Burkov

Reputation: 626

Laravel "Undefined offset: 4" exception when working with faker , how to remove the offset?

    public function run(){
    $types = ['Travelling','Camping','Restaurants','Food'];

    for ($i = 0; $i < 50; $i++){

        $faker = Factory::create();
        $internet = new Internet($faker);
        $date = new DateTime($faker);
        $lorem = new Lorem($faker);

        $id = $internet->numberBetween($min = 2000,$max = 2000000);
        $price = $internet->randomFloat($nbMaxDecimals = 2, $min = 0, $max = 100);
        $expiration = $date->dateTimeBetween($startDate = 'now', $endDate = '+2 years');
        $title = $lorem->sentence($nbWords = 3, $variableNbWords = true);

        DB::table('coupon')->insert([
            'id'=>$id,
            'title'=>$title,
            'price'=>$price,
            "type"=>$types[$i],
            'expiration'=>$expiration
        ]);
    }
}

The table updated by 4 rows. Need your help please can't understand how to overcome the offset limit ? Any additional configurations ?

Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined offset: 4","C:\xampp\htdocs\couponsystem\database\seeds\CouponSeeder.php")

Upvotes: 0

Views: 661

Answers (2)

Qonvex620
Qonvex620

Reputation: 3972

Definitely because your variable types is consist of 4 elements only and when the variable i in your foor loop is 4 then it will throw an error undifined offset 4. To solve this .

Change this , "type" => $types[$i]

To, "type" => $types[rand(0, 3)]

Upvotes: 0

Jerodev
Jerodev

Reputation: 33206

You $types array only has 4 elements, there is no index 4.

Use modulo 4 to make sure the number never goes over 3 and keeps looping from 0 to 3.

"type" => $types[$i % 4],

Upvotes: 2

Related Questions