1

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks a ton for both the editing and the answering. i felt real goofy. just recognized that i used $tasks instead of 'tasks'
@TheGripVic actually the normal behaviour would be to assume what you did, but every method has its peculiarities. Btw, A year and a half ago I was also just beginning with Laravel, now I know a little bit more -after a lot of mistakes, research, Laracasts and StackOverflow- So I can return the help received and I'm also to still learning. We are all here to improve, my friend. Have a good day.
@HCK nice copy pasting
Mate, I quoted your answer and added additional information (like docs) and also alternatives to achieve the same thing.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.