Undefined Offset Error

Published 1 week ago by JokersMild85

No idea why I am getting this error, can anyone provide some guidance?

public function store(Request $request)
{
    $values = $request->all();
    $id = Auth::id();
    
    echo "<h2>User ID: ".$id."</h2>";
    
    for($i=0;$i<count($values);$i++)
    {
        $e_id = $values['e_id'][$i];
        echo "<h4>Exercise ID: ".$e_id."</h4>";
        $sets = $values['sets'][$i];
        echo "<h4>Sets: ".$sets."</h4>";
        $reps = $values['reps'][$i];
        echo "<h4>Reps: ".$reps."</h4>";
    } 

}
Best Answer (As Selected By JokersMild85)
mfoote

Are you sure it’s not $id causing the issue? Try Auth::user()->id.

Lars-Janssen

One of these array indexes does not exists.

$values['e_id'][$i]
$values['sets'][$i]
$values['reps'][$i]
JokersMild85

They all exist. I'm inspecting the elements of the page and they are all returning values.

ejdelmonico

Run dd($values) to make sure the values are present. If they are, make sure the keys are correct. Something is not there in the array for that error to appear. If some values are allowed to be not required, then you will have to adjust your code to account for it.

JokersMild85

Yep, ran dd($values) after I selected 3 checkboxes and it returned 3 values for each array: sets, reps, and e_id. Not sure why it is looking for a 4th array key.

mfoote
mfoote
1 week ago (4,190 XP)

Are you sure it’s not $id causing the issue? Try Auth::user()->id.

Snapey
Snapey
1 week ago (678,595 XP)

err... the error message tells you what line is a problem

Snapey
Snapey
1 week ago (678,595 XP)

by the way, you are counting the number of attributes in the form request, and not the number of values in the arrays

Therefore if for example $request->all() is 7 fields then you are trying to loop over values 7 times therefore running off the end of the array.

try

for($i=0;$i<count($values['e_id']);$i++)
Snapey
Snapey
6 days ago (678,595 XP)

bonkers!

Please sign in or create an account to participate in this conversation.