mlussier17's avatar

Undefined Variable even tho it is defined

Hello, I have browsed many forum including this one and I can't figure out why my variable is undefined when I pass it to my view but when i "dd" my variable it shows my result set properly.

Here is my Controller

$results = [];
        do {
            try {
                $results[] = $stmt->fetchAll(\PDO::FETCH_OBJ);
            } catch (\Exception $ex) {

            }
        } while ($stmt->nextRowset());
//        dd($results);
        return view('timesheet.show', compact('results'));

And my view doesn't recognize my $result variable because it is "Undefined"

@if(isset($results))
                    @foreach($results as $result)
                        {{$result}}
                    @endforeach
                @endif

I have tried passing a random variable with a random value and tried to have it shown with no success. So my guess is probly somewhere else but can`t figure out where.

Any help will be appreciated. Thanks

0 likes
9 replies
Dalma's avatar

As a next step I would try to to dd your variable in your view

@php(dd($results))
Dalma's avatar

I also see that the $results variable is used within many of the laravel libraries perhaps you have encounted a variable collision. Have you tried a different variable name as well?

mlussier17's avatar

Yeah I have tried many variables name and harcoding a value to the variable with the same result. I have also tried

return view('timesheet.show', ['test' => '1']);

And showing $test in my view and still no result.

I'm working in my route file right now and maybe it was that beacause I can see a progress. Still not the result I want but no more undefined variable error.

Dalma's avatar

Which version of Laravel are you using?

Dalma's avatar

If you remove the references to the variable that you are trying to pass in does it actually render the view? Is it possible that that controller/method you are setting the variable in is NOT the one rendering your view? I have made this mistake myself.

mlussier17's avatar

Yes it did, I changed my code a round a bit and moved the return view to my route and now I can see my variable in my view.

Thanks for your help.

Please or to participate in this conversation.