1
votes

Hey guys I just started learning how to use Laravel and when I tried running the code below I get:

Undefined variable error

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <ul>
        @foreach ($tasks as $task)
            <li>{{ $task->Todo }}</li>
        @endforeach
    </ul>
</body>
</html>

this is the code used in the web.php file:

web.php

Route::get('/tasks', function () {
        $tasks = DB::table('tasks')->get();
    //return $tasks;
        return view('welcome',compact($tasks));
    });

I discovered that if I use the $GLOBALS['variable']; to replace the $tasks variable in both files it works.

But in the example video from laracasts they didn't make use of the $GLOBALS['variable'];

This is the error I get:

"Undefined variable: tasks (View: C:\Users\Friday\Documents\Documentations\laraprojects\BrainGear\resources\views\welcome.blade.php)"

2

2 Answers

3
votes

You need to pass the variable name in the compact() helper (as @utdev said). You can read more about this here. So:

return view('welcome', compact('tasks'));

Another option is to send the variable to the view like this:

return view('welcome')->with('tasks', $tasks);

or even "sugared" (equivalent to the last one):

return view('welcome')->withTasks($tasks);

To know more about this, check the Passing data to views section of the documentation.

0
votes

You have to return the variable like this:

    return view('welcome', compact('tasks'));

Then you can use it like you did but use lowercase for that case please:

    @foreach ($tasks as $task)
        <li>{{ $task->todo }}</li>
    @endforeach